import threading
import time

from .llm import call_structured_llm
from .schemas import SentimentResult, IssueResult, RiskResult, RoutingResult
from .state import FeedbackState


def _start(name: str):
    started = time.perf_counter()
    print(f"[START] {name} | thread={threading.current_thread().name}")
    return started


def _end(name: str, started: float):
    print(f"[END] {name} | {time.perf_counter() - started:.2f}s")


def sentiment_agent(state: FeedbackState):
    started = _start("Sentiment Agent")
    result = call_structured_llm(
        schema_name="sentiment_analysis",
        schema_model=SentimentResult,
        system_prompt=(
            "You are a customer sentiment specialist. Analyze only the supplied "
            "feedback. Classify sentiment, score frustration from 0 to 10, and "
            "give one concise evidence-based reason. Do not invent facts."
        ),
        feedback=state["feedback"],
    )
    _end("Sentiment Agent", started)
    return {"sentiment_result": result}


def issue_agent(state: FeedbackState):
    started = _start("Issue Agent")
    result = call_structured_llm(
        schema_name="issue_analysis",
        schema_model=IssueResult,
        system_prompt=(
            "You are a product feedback analyst. Identify the single primary "
            "issue type and summarize the core issue. If there is an explicit "
            "feature request, capture it; otherwise return null. Do not invent facts."
        ),
        feedback=state["feedback"],
    )
    _end("Issue Agent", started)
    return {"issue_result": result}


def risk_agent(state: FeedbackState):
    started = _start("Risk Agent")
    result = call_structured_llm(
        schema_name="urgency_churn_analysis",
        schema_model=RiskResult,
        system_prompt=(
            "You are a customer-risk analyst. Score urgency and churn risk from "
            "0 to 10 using only evidence in the feedback. Explicit deadlines, "
            "production blockers, security problems, repeated failures, cancellation "
            "or switching language should raise risk. Explain the strongest churn signal."
        ),
        feedback=state["feedback"],
    )
    _end("Risk Agent", started)
    return {"risk_result": result}


def routing_agent(state: FeedbackState):
    started = _start("Routing Agent")
    result = call_structured_llm(
        schema_name="department_routing",
        schema_model=RoutingResult,
        system_prompt=(
            "You route customer feedback to exactly one primary department. "
            "Choose Engineering for technical defects, Product for feature/design "
            "requests, Billing for charges/invoices/refunds, Security for access/privacy "
            "or data exposure, Support for general assistance, and Customer Success "
            "for relationship/adoption concerns. Give a short reason."
        ),
        feedback=state["feedback"],
    )
    _end("Routing Agent", started)
    return {"routing_result": result}
