"""بارگذاری و اعتبارسنجی System Prompt ایجنت‌ها از config/agents.yaml."""

from __future__ import annotations

import logging
from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
from typing import Optional

import yaml

logger = logging.getLogger(__name__)

AGENTS_FILE = Path(__file__).resolve().parent.parent / "config" / "agents.yaml"


@dataclass(frozen=True)
class Agent:
    id: str
    mention: str
    name: str
    role: str
    enabled: bool
    authority: str
    notion_db_key: Optional[str]
    system_prompt: str
    common_rules: str = field(default="", repr=False)
    source_rules: str = field(default="", repr=False)

    @property
    def full_system_prompt(self) -> str:
        """System Prompt نهایی = دستور نقش + قواعد مشترک + قواعد منابع داده."""
        parts = [self.system_prompt.strip(), self.common_rules.strip()]
        if self.source_rules:
            parts.append(self.source_rules.strip())
        return "\n\n".join(p for p in parts if p)


@dataclass(frozen=True)
class AgentRegistry:
    agents: dict[str, Agent]
    mention_index: dict[str, str]  # "@ag01" -> "AG01"

    def get(self, agent_id: str) -> Optional[Agent]:
        return self.agents.get(agent_id.upper())

    def enabled_agents(self) -> list[Agent]:
        return [a for a in self.agents.values() if a.enabled]

    def by_mention(self, mention: str) -> Optional[Agent]:
        agent_id = self.mention_index.get(mention.lower().strip())
        return self.agents.get(agent_id) if agent_id else None


@lru_cache(maxsize=1)
def load_registry(path: Path | None = None) -> AgentRegistry:
    file_path = path or AGENTS_FILE
    with file_path.open("r", encoding="utf-8") as fh:
        raw = yaml.safe_load(fh) or {}

    common = (raw.get("common_rules") or "").strip()
    src_rules = (raw.get("source_rules") or "").strip()
    agents: dict[str, Agent] = {}
    mentions: dict[str, str] = {}

    for item in raw.get("agents", []):
        agent_id = str(item["id"]).upper().strip()
        mention = str(item.get("mention") or f"@{agent_id.lower()}").lower().strip()
        agent = Agent(
            id=agent_id,
            mention=mention,
            name=item.get("name", agent_id),
            role=item.get("role", ""),
            enabled=bool(item.get("enabled", True)),
            authority=item.get("authority", ""),
            notion_db_key=item.get("notion_db_key"),
            system_prompt=(item.get("system_prompt") or "").strip(),
            common_rules=common,
            source_rules=src_rules,
        )
        agents[agent_id] = agent
        mentions[mention] = agent_id

    if not agents:
        raise RuntimeError(f"هیچ ایجنتی در {file_path} تعریف نشده است.")

    logger.info(
        "ایجنت‌ها بارگذاری شدند: %s | فعال: %s",
        ", ".join(agents),
        ", ".join(a.id for a in agents.values() if a.enabled),
    )
    return AgentRegistry(agents=agents, mention_index=mentions)
