"""User Aware Agent — personalised org snapshot delivery.

Receives a query from a user (or the RT agent via A2A), builds the daily org
snapshot from mock data, filters it to the caller's project membership and email
visibility, then responds in a style appropriate to their persona.

When the RT agent exists it will push a pre-built snapshot instead of this agent
computing it on demand — the tool interface stays the same.
"""

import os
from pathlib import Path

from loguru import logger as _log
from pydantic_ai import RunContext

from backend.chanakya.a2a_context import RequestContext, make_metadata_aware_app
from backend.chanakya.base import EnterpriseAgent
from backend.chanakya.config import AGENT_REGISTRY
from data.mock_data.snapshot import build_snapshot, filter_for_user
from data.mock_data.users import USERS
from pylogue.shell import app_factory as create_core_app

_cfg = AGENT_REGISTRY["user_aware"]

_USERS_BY_EMAIL = {u["email"]: u for u in USERS}

_USER_AWARE_AGENT_PROMPT = """\
You are the User Aware Agent for Tata Steel's Enterprise Brain platform.
Your job is to deliver a personalised daily briefing based on the caller's role and project membership.

Always call get_briefing first. Use the snapshot it returns to answer the user's question.
Shape your response to the caller's persona using the guidance in the snapshot's persona_instructions field.
If the caller is not a known user, return a clear error.
"""

_PERSONA_INSTRUCTIONS = {
    "c-suite": (
        "The user is a C-Suite executive. Be concise. Lead with the headline risk or status per project. "
        "Use bullet points. Skip operational detail — flag only things that need a decision or escalation."
    ),
    "manager": (
        "The user is a team lead or delivery manager. Provide project-level status with open ticket counts, "
        "blockers, and any emails requiring action. Include enough detail to act without drilling into raw data."
    ),
    "analyst": (
        "The user is an operations analyst. Provide full detail: all relevant emails, every open ticket with "
        "status and priority, and any anomalies in the data. Do not summarise away specifics."
    ),
}

user_aware_agent = EnterpriseAgent(
    api_base=os.environ["LITELLM_PROVIDER_BASE_URL"],
    instructions=_USER_AWARE_AGENT_PROMPT,
    logfire_env="chanakya-alpha",
    service_name="user_aware",
    deps_type=RequestContext,
)


@user_aware_agent.tool
def get_briefing(ctx: RunContext[RequestContext], date: str = "") -> str:
    """Build and return the filtered org snapshot for the calling user.

    Args:
        date: Snapshot date in YYYY-MM-DD format. Defaults to the latest data date (2026-03-20).
    """
    caller = ctx.deps.user_email
    _log.info("get_briefing CALLED caller={!r} date={!r}", caller, date)

    user = _USERS_BY_EMAIL.get(caller)
    if not user:
        _log.warning("get_briefing UNKNOWN USER caller={!r}", caller)
        return f"Unknown user: {caller}. No profile found in org directory."

    snapshot = build_snapshot(date or None)
    filtered = filter_for_user(snapshot, user)
    project_count = len(filtered["projects"])
    email_count = sum(len(p["emails"]) for p in filtered["projects"].values())
    ticket_count = sum(len(p["tickets"]) for p in filtered["projects"].values())
    _log.info("get_briefing SNAPSHOT projects={} emails={} tickets={}", project_count, email_count, ticket_count)

    persona = user.get("persona", "manager")
    persona_instructions = _PERSONA_INSTRUCTIONS.get(persona, _PERSONA_INSTRUCTIONS["manager"])

    lines = [
        f"PERSONA INSTRUCTIONS: {persona_instructions}",
        "",
        f"Briefing for {user['name']} ({user['role']}) — {filtered['date']}",
        f"Org: {filtered['org']}",
        "",
    ]

    for project_key, data in filtered["projects"].items():
        lines.append(f"## {project_key.replace('-', ' ').title()}")
        lines.append(f"Open tickets: {data['open_tickets']} | Critical: {data['critical_tickets']}")

        for t in data["tickets"]:
            lines.append(f"  [TICKET {t['id']}] {t['status']} | {t['priority']} | {t.get('snippet', t['summary'])}")

        for e in data["emails"]:
            lines.append(f"  [EMAIL {e['id']} {e['date']}] {e['from'].split('@')[0]} — {e.get('summary', e['subject'])}")

        lines.append("")

    payload = "\n".join(lines)
    _log.info("get_briefing RETURNING {} chars", len(payload))
    return payload


app = make_metadata_aware_app(
    user_aware_agent,
    name=_cfg.name,
    description=_cfg.description,
)


@app.on_event("startup")
async def _startup_banner() -> None:
    port = os.environ.get("USER_AWARE_AGENT_PORT", "8003")
    _log.info("\n  User Aware Agent ready:")
    _log.info("    A2A   → http://0.0.0.0:{}/", port)
    _log.info("    Chat  → http://0.0.0.0:{}/chat", port)
    _log.info("    Card  → http://0.0.0.0:{}/.well-known/agent-card.json", port)


_PROJECT_ROOT = Path(__file__).parents[3]
_db_path = os.environ.get(
    "PYLOGUE_DB_PATH",
    str(_PROJECT_ROOT / "data" / "conversation-histories" / "user-aware" / "chat_history.db"),
)
Path(_db_path).parent.mkdir(parents=True, exist_ok=True)

app.mount(
    "/chat",
    create_core_app(
        responder_factory=lambda: user_aware_agent,
        hero_title="User Aware Agent",
        hero_subtitle="Your personalised Tata Steel daily briefing.",
        db_path=_db_path,
    ),
)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(_cfg.module_path, host=_cfg.host, port=_cfg.port, reload=True)
