"""File-backed workspace agent registry."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from .models import RegisteredAgent


class AgentRegistry:
    def __init__(self, workspace: str | Path) -> None:
        self.workspace = Path(workspace)
        self.path = self.workspace / "agents" / "registry.json"
        self.path.parent.mkdir(parents=True, exist_ok=True)
        if not self.path.exists():
            self._write_agents([])
        else:
            self._drop_legacy_builtin_agents()

    def list_agents(self, *, include_disabled: bool = True) -> list[RegisteredAgent]:
        agents = self._read_agents()
        if include_disabled:
            return agents
        return [agent for agent in agents if agent.status == "active"]

    def list_active_agents(self) -> list[RegisteredAgent]:
        return self.list_agents(include_disabled=False)

    def get_agent(self, agent_id: str) -> RegisteredAgent | None:
        needle = agent_id.strip()
        for agent in self.list_agents():
            if agent.agent_id == needle:
                return agent
        return None

    def upsert_agent(self, payload: dict[str, Any] | RegisteredAgent) -> RegisteredAgent:
        agent = payload if isinstance(payload, RegisteredAgent) else RegisteredAgent.from_dict(payload)
        agents = self.list_agents()
        for index, existing in enumerate(agents):
            if existing.agent_id == agent.agent_id:
                if existing.source == "builtin" and agent.source == "workspace":
                    agent.source = "builtin"
                agent.created_at = existing.created_at
                agents[index] = agent
                self._write_agents(agents)
                return agent
        agents.append(agent)
        self._write_agents(agents)
        return agent

    def disable_agent(self, agent_id: str) -> RegisteredAgent:
        agents = self.list_agents()
        for index, agent in enumerate(agents):
            if agent.agent_id != agent_id:
                continue
            agent.status = "disabled"
            agents[index] = agent
            self._write_agents(agents)
            return agent
        raise ValueError(f"Unknown agent_id: {agent_id}")

    def delete_agent(self, agent_id: str) -> bool:
        target = agent_id.strip()
        if not target:
            return False
        agents = self.list_agents()
        kept = [agent for agent in agents if agent.agent_id != target]
        if len(kept) == len(agents):
            return False
        self._write_agents(kept)
        return True

    def search(
        self,
        *,
        role: str = "",
        capabilities: list[str] | None = None,
        tags: list[str] | None = None,
        skills: list[str] | None = None,
    ) -> list[RegisteredAgent]:
        role_terms = _terms(role)
        capability_terms = set(_terms(" ".join(capabilities or [])))
        tag_terms = set(_terms(" ".join(tags or [])))
        skill_terms = set(_terms(" ".join(skills or [])))
        matches: list[RegisteredAgent] = []
        for agent in self.list_active_agents():
            haystack = set(
                _terms(
                    " ".join(
                        [
                            agent.agent_id,
                            agent.name,
                            agent.display_name,
                            agent.role,
                            agent.description,
                            " ".join(agent.capabilities),
                            " ".join(agent.tags),
                            " ".join(agent.skill_names),
                        ]
                    )
                )
            )
            if role_terms and not role_terms.intersection(haystack):
                continue
            if capability_terms and not capability_terms.intersection(haystack):
                continue
            if tag_terms and not tag_terms.intersection(haystack):
                continue
            if skill_terms and not skill_terms.intersection(haystack):
                continue
            matches.append(agent)
        return matches

    def _read_agents(self) -> list[RegisteredAgent]:
        if not self.path.exists():
            return []
        payload = json.loads(self.path.read_text(encoding="utf-8"))
        raw_agents = payload.get("agents") if isinstance(payload, dict) else payload
        if not isinstance(raw_agents, list):
            return []
        return [RegisteredAgent.from_dict(item) for item in raw_agents if isinstance(item, dict)]

    def _write_agents(self, agents: list[RegisteredAgent]) -> None:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        payload = {"version": 1, "agents": [agent.to_dict() for agent in agents]}
        self.path.write_text(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")

    def _drop_legacy_builtin_agents(self) -> None:
        agents = self._read_agents()
        migrated = [agent for agent in agents if agent.source != "builtin"]
        if len(migrated) != len(agents):
            self._write_agents(migrated)


def _terms(text: str) -> set[str]:
    normalized = "".join(ch.lower() if ch.isalnum() else " " for ch in text)
    return {part for part in normalized.split() if part}

