"""ManualInputAdapter — routes user-entered content (inbox drops, CLI input) to agents.

LEGACY: This adapter is registered but not called from the runtime.
The canonical pipeline is: inbox watcher -> Charles LLM triage -> agent delegation.
Charles's triage prompt handles routing decisions dynamically via LLM, which is
more flexible than this adapter's keyword-based routing.
"""

from __future__ import annotations

import json
import logging
from datetime import UTC, datetime
from pathlib import Path

logger = logging.getLogger(__name__)


def _get_state_dir() -> Path:
    """Return state/content-bridge/manual directory (uses data root when set)."""
    from vastian.storage.data_root import get_data_root

    root = get_data_root(None)
    return root / "state" / "content-bridge" / "manual"


class ManualInputAdapter:
    """ContentBridge adapter for manual user input (inbox drops, CLI input)."""

    def get_target_agents(self, content: str, metadata: dict) -> list[str]:
        """Determine which agents should process this content.

        Uses content keywords to pick agents. metadata.target_agents override supported.
        """
        explicit = metadata.get("target_agents")
        if isinstance(explicit, list) and explicit:
            return list(explicit)
        if isinstance(explicit, str) and explicit:
            return [explicit.strip()]

        content_lower = content.lower()

        if "meeting" in content_lower or "transcript" in content_lower:
            return ["charles", "maya"]
        if "financial" in content_lower or "balance" in content_lower or "bank" in content_lower:
            return ["finley"]
        if "ticket" in content_lower or "task" in content_lower or "kanban" in content_lower:
            return ["arjuna", "liam"]
        if "vision" in content_lower or "strategy" in content_lower or "roadmap" in content_lower:
            return ["victor", "dominic"]
        if "knowledge" in content_lower or "research" in content_lower:
            return ["elias"]
        if "prompt" in content_lower or "drift" in content_lower or "audit" in content_lower:
            return ["theo"]
        if "scenario" in content_lower or "simulation" in content_lower:
            return ["concord", "kiran"]

        return ["charles"]

    def _detect_content_type(self, content: str, metadata: dict) -> str:
        """Infer content type from keywords for ingest result."""
        content_lower = content.lower()
        if "meeting" in content_lower or "transcript" in content_lower:
            return "meeting"
        if "financial" in content_lower or "balance" in content_lower or "bank" in content_lower:
            return "financial"
        if "ticket" in content_lower or "task" in content_lower or "kanban" in content_lower:
            return "task"
        if "vision" in content_lower or "strategy" in content_lower or "roadmap" in content_lower:
            return "strategy"
        if "knowledge" in content_lower or "research" in content_lower:
            return "research"
        if "prompt" in content_lower or "drift" in content_lower or "audit" in content_lower:
            return "audit"
        if "scenario" in content_lower or "simulation" in content_lower:
            return "simulation"
        return "general"

    async def ingest(self, content: str, metadata: dict) -> dict:
        """Process content and route to target agents.

        Returns:
            Dict with routed_to, content_type, and status.
        """
        agents = self.get_target_agents(content, metadata)
        content_type = self._detect_content_type(content, metadata)
        logger.info("Manual input ingested, routing to %s (type=%s)", agents, content_type)
        return {
            "routed_to": agents,
            "content_type": content_type,
            "status": "ingested",
        }

    def persist_outcomes(self, results: dict) -> None:
        """Write outcomes to state/content-bridge/manual/ as JSON."""
        out_dir = _get_state_dir()
        out_dir.mkdir(parents=True, exist_ok=True)
        timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
        filename = f"{timestamp}_manual.json"
        path = out_dir / filename
        try:
            path.write_text(json.dumps(results, indent=2, default=str), encoding="utf-8")
            logger.info("Persisted manual outcomes to %s", path)
        except OSError as e:
            logger.error("Failed to persist manual outcomes: %s", e)


def register() -> None:
    """Register the ManualInputAdapter with the loader."""
    from vastian.loader import register as loader_register

    loader_register("manual_content", ManualInputAdapter)
