# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Chairman Skill

Gives any agent the ability to consult the Chairman mid-task.
The Chairman knows the whole advisory team and can:
  - Decide whether another advisor should be looped in
  - Provide cross-domain context
  - Help frame a question for another specialist

Think of it as any advisor being able to call the Maître D'
and ask: "Should I bring in someone else for this?"
"""

import logging

logger = logging.getLogger(__name__)

SKILL_NAME = "chairman"
SKILL_DESCRIPTION = (
    "Consult the Chairman — the Round Table orchestrator who knows the full advisory team"
)


def query_chairman(data: dict) -> dict:
    """
    Ask the Chairman a question from within another agent's task.

    The Chairman knows every advisor on the team. Use this when:
    - You think another advisor should be looped in
    - You need cross-domain context beyond your own expertise
    - You want the Chairman to route a sub-question to the right specialist

    Args:
        question: The question to ask the Chairman
        context: Optional — brief summary of what you're currently working on

    Returns:
        Dict with Chairman's response and any recommended follow-up advisors
    """
    question = (data.get("question") or "").strip()
    context = (data.get("context") or "").strip()

    if not question:
        return {"error": "question is required"}

    try:
        from familiar.jobs.chairman import build_team_manifest

        team_manifest = build_team_manifest()

        # Build the Chairman message
        parts = [team_manifest, ""]
        if context:
            parts.append(f"**Current task context:** {context}\n")
        parts.append(f"**Question from an advisor:** {question}")

        chairman_message = "\n".join(parts)

        # Use the agent singleton with Chairman job class override
        from familiar.core.agent import get_agent  # type: ignore

        agent = get_agent()
        if agent is None:
            return {"error": "Agent not available"}

        result = agent.chat_with_results(
            chairman_message,
            user_id="chairman-consult",
            channel="internal",
            include_history=False,
            job_class_key="chairman",
        )

        # Try to parse structured response
        import json
        import re

        raw = result.text or ""
        match = re.search(r"```json\s*(.*?)\s*```", raw, re.DOTALL)
        if match:
            try:
                parsed = json.loads(match.group(1))
                return {
                    "chairman_response": parsed.get("response") or parsed.get("intro") or raw,
                    "action": parsed.get("action", "direct"),
                    "recommended_seats": parsed.get("seats", []),
                }
            except json.JSONDecodeError:
                pass

        return {"chairman_response": raw, "action": "direct", "recommended_seats": []}

    except Exception as e:
        logger.error("query_chairman failed: %s", e)
        return {"error": str(e)}


TOOLS = [
    {
        "name": "query_chairman",
        "description": (
            "Consult the Chairman of the Round Table — the orchestrator who knows every advisor on the team. "
            "Call this when you think another specialist should be looped in, when the question spans multiple domains, "
            "or when you need guidance on who else can help."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "question": {
                    "type": "string",
                    "description": "Your question for the Chairman",
                },
                "context": {
                    "type": "string",
                    "description": "Brief summary of the task you are currently working on (optional but helpful)",
                },
            },
            "required": ["question"],
        },
        "fn": query_chairman,
    },
]
