from collections import Counter
from .schemas import FinalAnalysis


def print_single_analysis(a: FinalAnalysis):
    print("\n" + "=" * 64)
    print("CUSTOMER FEEDBACK ANALYSIS")
    print("=" * 64)
    print(f"Customer:       {a.customer_id}")
    print(f"Feedback:       {a.feedback}")
    print(f"Sentiment:      {a.sentiment.sentiment.upper()}")
    print(f"Frustration:    {a.sentiment.frustration_score}/10")
    print(f"Issue Type:     {a.issue.issue_type}")
    print(f"Core Issue:     {a.issue.issue}")
    print(f"Urgency:        {a.risk.urgency_score}/10")
    print(f"Churn Risk:     {a.risk.churn_risk_score}/10")
    print(f"Department:     {a.routing.department}")
    print(f"Priority:       {a.priority_score}/100 — {a.priority_level}")
    print("=" * 64)


def print_batch_report(results: list[FinalAnalysis]):
    sentiment_counts = Counter(x.sentiment.sentiment for x in results)
    issue_counts = Counter(x.issue.issue_type for x in results)
    department_counts = Counter(x.routing.department for x in results)
    priority_counts = Counter(x.priority_level for x in results)

    ranked = sorted(results, key=lambda x: x.priority_score, reverse=True)

    print("\n" + "=" * 72)
    print("CUSTOMER FEEDBACK INTELLIGENCE REPORT")
    print("=" * 72)
    print(f"Reviews analyzed: {len(results)}")

    print("\nSENTIMENT")
    for key in ["negative", "neutral", "positive"]:
        print(f"  {key.title():<10} {sentiment_counts[key]}")

    print("\nISSUE TYPES")
    for name, count in issue_counts.most_common():
        print(f"  {name:<20} {count}")

    print("\nPRIORITY")
    for key in ["CRITICAL", "HIGH", "MEDIUM", "LOW"]:
        print(f"  {key:<10} {priority_counts[key]}")

    print("\nDEPARTMENT ROUTING")
    for name, count in department_counts.most_common():
        print(f"  {name:<20} {count}")

    print("\nTOP 10 PRIORITY CUSTOMERS")
    for idx, item in enumerate(ranked[:10], start=1):
        print(
            f"  {idx:>2}. {item.customer_id} | "
            f"{item.priority_score:>5.1f} {item.priority_level:<8} | "
            f"{item.routing.department:<16} | {item.issue.issue}"
        )

    if ranked:
        top = ranked[0]
        print("\nTOP PRIORITY CUSTOMER")
        print(f"  Customer:    {top.customer_id}")
        print(f"  Issue:       {top.issue.issue}")
        print(f"  Urgency:     {top.risk.urgency_score}/10")
        print(f"  Churn Risk:  {top.risk.churn_risk_score}/10")
        print(f"  Department:  {top.routing.department}")
        print(f"  Priority:    {top.priority_score}/100 — {top.priority_level}")

    print("=" * 72)
