"""Mock provider — simulates the full call lifecycle locally.

Drives the exact same event handlers the real platform hits, with a
deterministic transcript/score derived from the candidate profile (reusing
the reports module's scoring heuristics). Keeps the whole module demoable
end-to-end with no connectivity, GPUs or telephony."""

import uuid

from django.conf import settings

from apps.reports.report_ai import build_scores, classify

from .. import queue
from .base import BaseProvider


class MockProvider(BaseProvider):
    name = "mock"

    def start_call(self, ai_call):
        call_id = f"mock-{uuid.uuid4().hex[:12]}"
        _schedule_mock_lifecycle(ai_call.id, call_id)
        return call_id

    def cancel_call(self, ai_call):
        # The pending timers check status before completing, so flipping the
        # status (done by the cancel view) is enough to stop the simulation.
        return True


def _mock_utterances(variables, score):
    """Simulated conversation as structured utterances (speaker + text)."""
    name = variables.get("candidate_name") or "the candidate"
    title = variables.get("job_title") or "the role"
    skills = (variables.get("required_skills") or "the required stack").strip()
    location = variables.get("job_location") or "as discussed"
    return [
        ("AGENT", f"Hello, am I speaking with {name}?"),
        ("CANDIDATE", "Yes, speaking."),
        ("AGENT", f"Great! I'm calling from the recruitment team regarding the {title} position. "
                  "Is this a good time for a quick screening conversation?"),
        ("CANDIDATE", "Yes, sure."),
        ("AGENT", f"Could you walk me through your experience with {skills}?"),
        ("CANDIDATE", "I have hands-on experience with several of those areas and described my recent projects."),
        ("AGENT", "What is your current notice period and expected compensation?"),
        ("CANDIDATE", "I shared my notice period and expectations."),
        ("AGENT", f"Are you comfortable with the role's location ({location})?"),
        ("CANDIDATE", "Yes, that works for me."),
        ("AGENT", "Thank you for your time! Our team will follow up with the next steps shortly."),
    ]


def _schedule_mock_lifecycle(ai_call_id, call_id):
    """Simulate the platform's event sequence with realistic short delays."""
    from .. import services  # late import to avoid a cycle
    from ..models import AICall

    def dial():
        services.handle_status_event({"call_id": call_id, "status": "in_progress"})

    def complete():
        ai_call = AICall.objects.filter(pk=ai_call_id).first()
        if not ai_call or ai_call.provider_call_id != call_id:
            return  # superseded by a retry
        if ai_call.status not in (AICall.Status.QUEUED, AICall.Status.DIALING, AICall.Status.IN_PROGRESS):
            return  # cancelled meanwhile

        scores, _ = build_scores(ai_call.candidate, ai_call.application)
        score = scores["overall"]
        variables = ai_call.agent_variables
        pairs = _mock_utterances(variables, score)
        utterances = [
            {
                "sequence": i,
                "speaker": speaker,
                "message": message,
                "started_ms": i * 9000,
                "ended_ms": i * 9000 + 6000,
                "language": "en",
            }
            for i, (speaker, message) in enumerate(pairs, start=1)
        ]
        services.handle_transcript_event({"call_id": call_id, "utterances": utterances})
        services.handle_completed_event({
            "call_id": call_id,
            "status": "completed",
            "duration": 180 + (ai_call.candidate_id * 7) % 240,
            "score": score,
            "summary": (
                f"{variables.get('candidate_name')} was screened for {variables.get('job_title')}. "
                f"Overall screening score {score}/100 ({classify(score)}). "
                "Key skills, notice period and location fit were discussed on the call."
            ),
            "recommendation": "QUALIFIED" if score >= settings.AI_QUALIFY_THRESHOLD else "NOT_QUALIFIED",
            "evaluation": {
                "technical_score": scores["technical"],
                "communication_score": scores["communication"],
                "experience_score": scores["experience_match"],
                "confidence_score": scores["problem_solving"],
                "overall_score": score,
                "classification": (
                    "Strong Match" if score >= 75 else "Potential Match" if score >= 55 else "Not Suitable"
                ),
                "recommendation": (
                    "Proceed" if score >= settings.AI_QUALIFY_THRESHOLD
                    else "Hold" if score >= 45 else "Reject"
                ),
                "strengths": ["Relevant skill overlap", "Clear communication on the call"],
                "weaknesses": ["Simulated call — verify in a live interview"],
                "summary": f"Simulated evaluation with overall score {score}/100.",
                "rubric": {"simulated": True},
            },
        })

    queue.spawn_later(2, dial)
    queue.spawn_later(8, complete)
