from .schemas import FinalAnalysis
from .state import FeedbackState


SENTIMENT_SEVERITY = {
    "positive": 0,
    "neutral": 4,
    "negative": 10,
}


def calculate_priority_score(state: FeedbackState) -> float:
    """
    Convert three 0-10 signals into a deterministic 0-100 score.

    40% urgency + 35% churn risk + 25% sentiment severity.
    """
    urgency = state["risk_result"].urgency_score * 10
    churn = state["risk_result"].churn_risk_score * 10
    sentiment = SENTIMENT_SEVERITY[state["sentiment_result"].sentiment] * 10

    score = (urgency * 0.40) + (churn * 0.35) + (sentiment * 0.25)
    return round(score, 1)


def priority_level(score: float) -> str:
    if score <= 30:
        return "LOW"
    if score <= 60:
        return "MEDIUM"
    if score <= 80:
        return "HIGH"
    return "CRITICAL"


def aggregate_results(state: FeedbackState):
    score = calculate_priority_score(state)

    final = FinalAnalysis(
        customer_id=state["customer_id"],
        feedback=state["feedback"],
        sentiment=state["sentiment_result"],
        issue=state["issue_result"],
        risk=state["risk_result"],
        routing=state["routing_result"],
        priority_score=score,
        priority_level=priority_level(score),
    )

    return {"final_analysis": final}
