"""Project Manager dashboard — scoped analytics over the PM's own requirements.

GET /api/dashboard/project-manager/  (also under /api/v1/dashboard/)

Everything is scoped to JDs created/owned by the logged-in user. Counts are
derived live from pipeline stages (data-driven PipelineStage master):

    submitted       reached the `submitted` stage or beyond
    shortlisted     reached the `selected` stage or beyond (client shortlist)
    offered         reached the `offered` stage or beyond
    joined          current stage outcome WON (`placed`)
    offer_rejected  currently in `offer_declined` / `offered_not_joined`
    rejected        current stage outcome LOST (any rejection stage)

"Reached or beyond" counts WON candidates and post-milestone LOST candidates
(e.g. an offer-decliner certainly reached `submitted`), so numbers never
shrink as candidates progress.
"""

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

from core.responses import success_response

from apps.jobs.models import JDRecruiterAssignment, JobDescription
from apps.pipeline.models import JobApplication
from apps.pipeline.pm_metrics import METRIC_KEYS, classify as _classify, get_thresholds

STATUS_LABELS = {"Published": "Open", "Draft": "Draft", "Closed": "Closed"}


class ProjectManagerDashboardView(APIView):
    """Requirement-wise analytics for the logged-in Project Manager."""

    permission_classes = [IsAuthenticated]

    def get(self, request):
        jobs = list(
            JobDescription.objects.filter(created_by=request.user)
            .select_related("client")
            .prefetch_related("assigned_recruiters")
            .order_by("-created_at")
        )
        job_ids = [j.id for j in jobs]

        thresholds = get_thresholds()

        per_job = {jid: dict.fromkeys(METRIC_KEYS, 0) for jid in job_ids}
        applications = (
            JobApplication.objects.filter(job_id__in=job_ids, candidate__is_deleted=False)
            .select_related("stage")
        )
        for app in applications:
            for key in _classify(app.stage, thresholds):
                per_job[app.job_id][key] += 1

        assigned_total = (
            JDRecruiterAssignment.objects.filter(jd_id__in=job_ids)
            .values("recruiter_id").distinct().count()
        )

        requirements = []
        for job in jobs:
            counts = per_job[job.id]
            requirements.append({
                "jd_id": job.id,
                "jd_code": f"JD-{job.id:04d}",
                "jd_title": job.title,
                "client_name": job.client.name if job.client else "",
                "created_date": job.created_at.strftime("%Y-%m-%d"),
                "assigned_recruiters_count": job.assigned_recruiters.count(),
                **counts,
                "status": STATUS_LABELS.get(job.status, job.status),
            })

        totals = {key: sum(r[key] for r in requirements) for key in METRIC_KEYS}
        return success_response({
            "total_requirements": len(jobs),
            "assigned_recruiters": assigned_total,
            **totals,
            "requirements": requirements,
        })
