from collections import Counter
from pathlib import Path

from .schemas import FinalAnalysis


def load_analyzed_reviews(path: str | Path) -> list[FinalAnalysis]:
    path = Path(path)
    if not path.exists():
        return []

    results = []
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            if line.strip():
                results.append(FinalAnalysis.model_validate_json(line))
    return results


def build_dashboard_payload(results: list[FinalAnalysis]) -> dict:
    if not results:
        return {
            "summary": {"total_reviews": 0, "critical_count": 0, "negative_count": 0, "avg_priority": 0},
            "sentiment": {}, "issue_types": {}, "priority": {}, "departments": {}, "reviews": [],
        }

    sentiment = Counter(x.sentiment.sentiment for x in results)
    issue_types = Counter(x.issue.issue_type for x in results)
    priority = Counter(x.priority_level for x in results)
    departments = Counter(x.routing.department for x in results)
    ranked = sorted(results, key=lambda x: x.priority_score, reverse=True)

    return {
        "summary": {
            "total_reviews": len(results),
            "critical_count": priority["CRITICAL"],
            "negative_count": sentiment["negative"],
            "avg_priority": round(sum(x.priority_score for x in results) / len(results), 1),
        },
        "sentiment": dict(sentiment),
        "issue_types": dict(issue_types),
        "priority": dict(priority),
        "departments": dict(departments),
        "reviews": [
            {
                "customer_id": x.customer_id,
                "feedback": x.feedback,
                "sentiment": x.sentiment.sentiment,
                "frustration_score": x.sentiment.frustration_score,
                "sentiment_reason": x.sentiment.reason,
                "issue_type": x.issue.issue_type,
                "issue": x.issue.issue,
                "feature_request": x.issue.feature_request,
                "urgency_score": x.risk.urgency_score,
                "churn_risk_score": x.risk.churn_risk_score,
                "churn_signal": x.risk.churn_signal,
                "department": x.routing.department,
                "routing_reason": x.routing.reason,
                "priority_score": x.priority_score,
                "priority_level": x.priority_level,
            }
            for x in ranked
        ],
    }
