"""Org snapshot builder — assembles a daily view of all projects from mock data.

The snapshot is the unit the user-aware agent operates on.
When the RT agent exists, it will push a pre-built snapshot instead of this module
computing it on demand.

Shape:
    {
        "date": "2026-03-15",
        "org": "Tata Steel",
        "projects": {
            "bf3-coal-supply": {
                "emails": [...],        # emails dated <= snapshot_date, project-tagged
                "tickets": [...],       # tickets created <= snapshot_date, project-tagged
                "open_tickets": int,
                "critical_tickets": int,
            },
            ...
        }
    }
"""

from __future__ import annotations

from datetime import date

from data.mock_data.emails import EMAILS
from data.mock_data.tickets import TICKETS

_PROJECTS = [
    "bf3-coal-supply",
    "die-casting-maintenance",
    "iron-ore-ops",
    "safety-compliance",
    "enterprise-brain",
    "client-delivery",
    "q2-capacity-planning",
]


def build_snapshot(snapshot_date: str | date | None = None) -> dict:
    """Build the org snapshot for a given date (defaults to latest data date).

    Only includes emails and tickets on or before snapshot_date so the agent
    sees a point-in-time view, not the full history.
    """
    if snapshot_date is None:
        snapshot_date = "2026-03-20"
    cutoff = str(snapshot_date)

    projects: dict[str, dict] = {}
    for project in _PROJECTS:
        emails = [
            e for e in EMAILS
            if e.get("project") == project and e["date"] <= cutoff
        ]
        tickets = [
            t for t in TICKETS
            if t.get("project") == project and t["created"] <= cutoff
        ]
        open_tickets = [t for t in tickets if t["status"] not in ("Done",)]
        critical = [t for t in open_tickets if t["priority"] == "Critical"]

        projects[project] = {
            "emails": emails,
            "tickets": tickets,
            "open_tickets": len(open_tickets),
            "critical_tickets": len(critical),
        }

    return {
        "date": cutoff,
        "org": "Tata Steel",
        "projects": projects,
    }


def filter_for_user(snapshot: dict, user: dict) -> dict:
    """Return a copy of the snapshot containing only projects the user is on,
    and only emails visible to that user.
    """
    user_email = user["email"]
    user_projects = set(user.get("projects", []))

    filtered_projects: dict[str, dict] = {}
    for project_key, project_data in snapshot["projects"].items():
        if project_key not in user_projects:
            continue

        visible_emails = [
            e for e in project_data["emails"]
            if user_email in e.get("recipients_visible_to", [])
        ]
        filtered_projects[project_key] = {
            **project_data,
            "emails": visible_emails,
        }

    return {
        **snapshot,
        "projects": filtered_projects,
    }
