from django.conf import settings
from django.db import models


class Report(models.Model):
    """Permission anchor only — no DB table is created (managed = False).

    Exists so the app owns a `reports.view_reports` custom permission that
    gates the whole Reports module: the sidebar menu (Menu.permission_code)
    and every /api/v1/reports/ endpoint. ADMIN users bypass it; manager
    roles receive it via their group (see add_reports_menu.py)."""

    class Meta:
        managed = False
        default_permissions = ()
        permissions = [("view_reports", "Can view reports")]


class CandidateReport(models.Model):
    """A generated, versioned PDF evaluation report for a candidate.

    Every generate/regenerate creates a new row (report_version increments),
    so history is preserved. `payload` snapshots all generated content
    (profile, scores, AI summary/recommendation) at generation time — the
    viewer renders it without recomputing, and the PDF matches it exactly.

    The auto view permission (reports.view_candidatereport) gates the menu
    item and is granted to manager groups AND the RECRUITER group; recruiters
    only ever see candidates on JDs assigned to them (scoped in the views)."""

    class Classification(models.TextChoices):
        HIGHLY_RECOMMENDED = "Highly Recommended", "Highly Recommended"
        RECOMMENDED = "Recommended", "Recommended"
        CONSIDER = "Consider", "Consider"
        NOT_RECOMMENDED = "Not Recommended", "Not Recommended"

    candidate = models.ForeignKey(
        "candidates.Candidate", on_delete=models.CASCADE, related_name="reports"
    )
    application = models.ForeignKey(
        "pipeline.JobApplication", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="reports", help_text="The JD pipeline entry this report evaluates against.",
    )
    pdf_file = models.FileField(upload_to="candidate_reports/", null=True, blank=True)
    generated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="candidate_reports_generated",
    )
    generated_at = models.DateTimeField()
    report_version = models.PositiveIntegerField(default=1)
    classification = models.CharField(
        max_length=30, choices=Classification.choices, default=Classification.CONSIDER
    )
    overall_score = models.PositiveSmallIntegerField(null=True, blank=True)
    recommendation_summary = models.TextField(blank=True, default="")
    payload = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "candidate_reports"
        ordering = ["-id"]
        unique_together = ("candidate", "report_version")

    def __str__(self):
        return f"Report v{self.report_version} for candidate {self.candidate_id}"
