# ============================================================
# ADDITIVE: Performance Management & OKRs - models
# ------------------------------------------------------------
# Nothing existing is touched. These models sit next to the
# existing ones and add what the "Performance Management & OKRs"
# screens need.
#
# DUPLICATE CHECK (all existing models were reviewed first):
#   Employee.Target             -> simple per-employee target. NOT reused as the
#                                  OKR table (no progress / weight / cycle), but
#                                  linked through PerfGoal.legacy_target and can
#                                  be imported with POST goals/import-targets/.
#   People.PromotionRequest     -> REUSED for promotions. PerfAppraisal only keeps
#                                  a nullable link (promotion_request) - no second
#                                  promotion model.
#   People.ConfirmationReview   -> probation review. Different purpose, untouched.
#   Recruitment.InterviewFeedback -> hiring feedback. Different purpose, untouched.
#
# Screen tab                  -> model
# -----------------------------------------------------------
# Performance Dashboard       -> aggregates PerfAppraisal / PerfGoal / PerfImprovementPlan
# Goals / KPIs                -> PerfGoal            (objective / key result / KPI)
# Appraisals                  -> PerfAppraisal       (self + manager score, promotion)
# Review Cycles               -> PerfReviewCycle
# Manager Feedback            -> PerfManagerFeedback (1-on-1 dossiers)
# Employee Self Review        -> PerfSelfReview
# Rating History              -> PerfRatingHistory   (bell curve source)
# "Performance PIPs" card     -> PerfImprovementPlan
#
# This module is imported at the very bottom of Employee/models.py
# (one additive line) so Django registers the models in the
# "Employee" app - the same way leave_models.py is registered.
# ============================================================

from decimal import Decimal

from django.db import models
from django.db.models import Q

from Company.models import company_details


__all__ = [
    "PerfReviewCycle", "PerfGoal", "PerfAppraisal", "PerfSelfReview",
    "PerfManagerFeedback", "PerfImprovementPlan", "PerfRatingHistory",
]


# ------------------------------------------------------------
# choices
# ------------------------------------------------------------

CYCLE_TYPE_CHOICES = [
    ("Mid-Year", "Mid-Year"),
    ("Annual", "Annual"),
    ("Quarterly", "Quarterly"),
    ("Goal Setting", "Goal Setting"),
    ("Executive Review", "Executive Review"),
    ("Custom", "Custom"),
]

CYCLE_STATUS_CHOICES = [
    ("Draft", "Draft"),
    ("Active", "Active"),
    ("Closed", "Closed"),
]

GOAL_TYPE_CHOICES = [
    ("Objective", "Objective"),
    ("Key Result", "Key Result"),
    ("KPI", "KPI"),
]

GOAL_STATUS_CHOICES = [
    ("Not Started", "Not Started"),
    ("In Progress", "In Progress"),
    ("At Risk", "At Risk"),
    ("Completed", "Completed"),
    ("Cancelled", "Cancelled"),
]

APPRAISAL_STATUS_CHOICES = [
    ("Pending Self Review", "Pending Self Review"),
    ("Pending Manager Review", "Pending Manager Review"),
    ("Calibration", "Calibration"),
    ("Completed", "Completed"),
]

POTENTIAL_CHOICES = [
    ("Low", "Low"),
    ("Medium", "Medium"),
    ("High", "High"),
]

SELF_REVIEW_STATUS_CHOICES = [
    ("Draft", "Draft"),
    ("Submitted", "Submitted"),
]

FEEDBACK_TYPE_CHOICES = [
    ("1-on-1", "1-on-1"),
    ("Mid-Year", "Mid-Year"),
    ("Annual", "Annual"),
    ("Coaching", "Coaching"),
    ("Recognition", "Recognition"),
]

PIP_STATUS_CHOICES = [
    ("Active", "Active"),
    ("Extended", "Extended"),
    ("Completed", "Completed"),
    ("Cancelled", "Cancelled"),
]

HISTORY_SOURCE_CHOICES = [
    ("appraisal", "Appraisal"),
    ("manual", "Manual"),
    ("import", "Import"),
]


class _PerfAudit(models.Model):
    """Same audit convention as the rest of the project."""

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    created_by = models.CharField(max_length=150, null=True, blank=True)
    updated_by = models.CharField(max_length=150, null=True, blank=True)

    id_version = models.PositiveIntegerField(default=1)

    class Meta:
        abstract = True


# ============================================================
# REVIEW CYCLE  (Review Cycles tab)
# ============================================================

class PerfReviewCycle(_PerfAudit):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="perf_review_cycles",
    )

    name = models.CharField(
        max_length=150,
        help_text="e.g. Mid-Year Performance Review (H1 2026)",
    )

    cycle_type = models.CharField(
        max_length=20, choices=CYCLE_TYPE_CHOICES, default="Custom",
    )

    period_label = models.CharField(
        max_length=50, blank=True, default="",
        help_text="Short label used by the dashboard, e.g. H1 2026",
    )

    financial_year = models.CharField(
        max_length=9, blank=True, default="",
        help_text="April-March, e.g. 2026-27",
    )

    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)

    submission_deadline = models.DateField(null=True, blank=True)

    eligible_joined_before = models.DateField(
        null=True, blank=True,
        help_text="Eligible: all employees who joined before this date. Empty = everyone",
    )

    description = models.TextField(blank=True, default="")

    status = models.CharField(
        max_length=10, choices=CYCLE_STATUS_CHOICES, default="Draft", db_index=True,
    )

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["-submission_deadline", "-id"]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "name"],
                name="unique_company_perf_cycle_name",
            )
        ]

    def __str__(self):
        return f"{self.company_id} - {self.name} ({self.status})"


# ============================================================
# GOALS / KPIs / OKRs  (Goals / KPIs tab)
# ============================================================

class PerfGoal(_PerfAudit):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="perf_goals",
    )

    employee = models.ForeignKey(
        "Employee.EmployeeDT", on_delete=models.CASCADE,
        related_name="perf_goals",
    )

    cycle = models.ForeignKey(
        PerfReviewCycle, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="goals",
    )

    # OKR tree: a Key Result can hang under an Objective
    parent = models.ForeignKey(
        "self", on_delete=models.CASCADE,
        null=True, blank=True, related_name="children",
    )

    # link to the OLD simple Employee.Target row (no duplicate data)
    legacy_target = models.ForeignKey(
        "Employee.Target", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="perf_goals",
    )

    title = models.CharField(max_length=255)

    description = models.TextField(blank=True, default="")

    goal_type = models.CharField(
        max_length=12, choices=GOAL_TYPE_CHOICES, default="Objective",
    )

    financial_year = models.CharField(max_length=9, blank=True, default="")

    weight = models.DecimalField(
        max_digits=5, decimal_places=2, default=Decimal("0"),
        help_text="Weightage (%) of this goal in the appraisal",
    )

    target_value = models.DecimalField(
        max_digits=14, decimal_places=2, null=True, blank=True,
    )

    current_value = models.DecimalField(
        max_digits=14, decimal_places=2, null=True, blank=True,
    )

    unit = models.CharField(max_length=30, blank=True, default="")

    progress_percent = models.DecimalField(
        max_digits=5, decimal_places=2, default=Decimal("0"),
        help_text="0 - 100. Auto-calculated from current/target when both are sent",
    )

    start_date = models.DateField(null=True, blank=True)
    due_date = models.DateField(null=True, blank=True)

    status = models.CharField(
        max_length=12, choices=GOAL_STATUS_CHOICES, default="Not Started", db_index=True,
    )

    completed_at = models.DateTimeField(null=True, blank=True)

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["employee_id", "id"]
        indexes = [
            models.Index(fields=["company", "employee"]),
            models.Index(fields=["company", "status"]),
        ]

    def __str__(self):
        return f"{self.employee_id} - {self.title} ({self.progress_percent}%)"


# ============================================================
# APPRAISAL  (Appraisals tab)
# ============================================================

class PerfAppraisal(_PerfAudit):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="perf_appraisals",
    )

    employee = models.ForeignKey(
        "Employee.EmployeeDT", on_delete=models.CASCADE,
        related_name="perf_appraisals",
    )

    cycle = models.ForeignKey(
        PerfReviewCycle, on_delete=models.CASCADE,
        related_name="appraisals",
    )

    financial_year = models.CharField(max_length=9, blank=True, default="")

    self_score = models.DecimalField(
        max_digits=3, decimal_places=1, null=True, blank=True,
    )

    manager_score = models.DecimalField(
        max_digits=3, decimal_places=1, null=True, blank=True,
    )

    # Normalized rating = manager score unless HR calibrates it.
    normalized_rating = models.DecimalField(
        max_digits=3, decimal_places=1, null=True, blank=True,
    )

    is_calibrated = models.BooleanField(
        default=False,
        help_text="True once HR set normalized_rating by hand (calibration)",
    )

    # optional custom badge text, e.g. "Visionary Leadership".
    # Empty = derived from the rating band.
    rating_label_override = models.CharField(max_length=60, blank=True, default="")

    potential = models.CharField(
        max_length=6, choices=POTENTIAL_CHOICES, blank=True, default="",
        help_text="9-box potential axis. High = 'High Potential Talent' card",
    )

    nine_box_position = models.CharField(max_length=60, blank=True, default="")

    promotion_proposed = models.BooleanField(default=False)

    proposed_level = models.CharField(max_length=30, blank=True, default="")

    # REUSES the existing People.PromotionRequest (no duplicate model)
    promotion_request = models.ForeignKey(
        "People.PromotionRequest", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="+",
    )

    reviewer_code = models.CharField(
        max_length=100, blank=True, default="",
        help_text="employee_code of the manager who reviews",
    )

    manager_comments = models.TextField(blank=True, default="")
    hr_comments = models.TextField(blank=True, default="")

    status = models.CharField(
        max_length=24, choices=APPRAISAL_STATUS_CHOICES,
        default="Pending Self Review", db_index=True,
    )

    completed_at = models.DateTimeField(null=True, blank=True)

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["-id"]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "employee", "cycle"],
                name="unique_company_employee_cycle_appraisal",
            )
        ]
        indexes = [
            models.Index(fields=["company", "status"]),
        ]

    def save(self, *args, **kwargs):
        # normalized rating follows the manager score until calibrated
        if not self.is_calibrated:
            self.normalized_rating = self.manager_score
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.employee_id} / cycle {self.cycle_id} ({self.status})"


# ============================================================
# EMPLOYEE SELF REVIEW  (Employee Self Review tab)
# ============================================================

class PerfSelfReview(_PerfAudit):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="perf_self_reviews",
    )

    employee = models.ForeignKey(
        "Employee.EmployeeDT", on_delete=models.CASCADE,
        related_name="perf_self_reviews",
    )

    cycle = models.ForeignKey(
        PerfReviewCycle, on_delete=models.CASCADE,
        related_name="self_reviews",
    )

    appraisal = models.ForeignKey(
        PerfAppraisal, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="self_reviews",
    )

    summary = models.TextField(
        help_text="Self-appraisal text, e.g. 'Delivered the 1-Click candidate conversion engine ...'",
    )

    self_score = models.DecimalField(
        max_digits=3, decimal_places=1, null=True, blank=True,
    )

    status = models.CharField(
        max_length=10, choices=SELF_REVIEW_STATUS_CHOICES, default="Draft",
    )

    submitted_at = models.DateTimeField(null=True, blank=True)

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["-id"]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "employee", "cycle"],
                name="unique_company_employee_cycle_self_review",
            )
        ]

    def __str__(self):
        return f"{self.employee_id} self review / cycle {self.cycle_id} ({self.status})"


# ============================================================
# MANAGER FEEDBACK  (Manager Feedback tab - 1-on-1 dossiers)
# ============================================================

class PerfManagerFeedback(_PerfAudit):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="perf_manager_feedback",
    )

    # the person the feedback is ABOUT
    employee = models.ForeignKey(
        "Employee.EmployeeDT", on_delete=models.CASCADE,
        related_name="perf_feedback_received",
    )

    # the manager who WROTE it
    manager = models.ForeignKey(
        "Employee.EmployeeDT", on_delete=models.SET_NULL,
        null=True, blank=True, related_name="perf_feedback_given",
    )

    cycle = models.ForeignKey(
        PerfReviewCycle, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="manager_feedback",
    )

    feedback_type = models.CharField(
        max_length=12, choices=FEEDBACK_TYPE_CHOICES, default="1-on-1",
    )

    feedback = models.TextField()

    rating = models.DecimalField(
        max_digits=3, decimal_places=1, null=True, blank=True,
    )

    meeting_date = models.DateField(null=True, blank=True)

    visible_to_employee = models.BooleanField(
        default=False,
        help_text="False = confidential dossier (HR + manager only)",
    )

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["-meeting_date", "-id"]
        indexes = [
            models.Index(fields=["company", "employee"]),
        ]

    def __str__(self):
        return f"{self.manager_id} on {self.employee_id} ({self.feedback_type})"


# ============================================================
# PERFORMANCE IMPROVEMENT PLAN  (dashboard "Performance PIPs" card)
# ============================================================

class PerfImprovementPlan(_PerfAudit):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="perf_improvement_plans",
    )

    employee = models.ForeignKey(
        "Employee.EmployeeDT", on_delete=models.CASCADE,
        related_name="perf_improvement_plans",
    )

    appraisal = models.ForeignKey(
        PerfAppraisal, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="improvement_plans",
    )

    reason = models.TextField(blank=True, default="")
    coaching_plan = models.TextField(blank=True, default="")

    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)

    status = models.CharField(
        max_length=10, choices=PIP_STATUS_CHOICES, default="Active", db_index=True,
    )

    outcome = models.TextField(blank=True, default="")

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["-id"]

    def __str__(self):
        return f"PIP {self.employee_id} ({self.status})"


# ============================================================
# RATING HISTORY  (Rating History tab - bell curve source)
# ============================================================

class PerfRatingHistory(_PerfAudit):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="perf_rating_history",
    )

    employee = models.ForeignKey(
        "Employee.EmployeeDT", on_delete=models.CASCADE,
        related_name="perf_rating_history",
    )

    cycle = models.ForeignKey(
        PerfReviewCycle, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="rating_history",
    )

    appraisal = models.ForeignKey(
        PerfAppraisal, on_delete=models.SET_NULL,
        null=True, blank=True, related_name="rating_history",
    )

    period_label = models.CharField(max_length=50, blank=True, default="")

    financial_year = models.CharField(max_length=9, blank=True, default="")

    rating = models.DecimalField(max_digits=3, decimal_places=1)

    # 1..5 - derived from rating (floor), stored so the bell curve is one GROUP BY
    rating_bucket = models.PositiveSmallIntegerField(default=1, db_index=True)

    rating_label = models.CharField(max_length=60, blank=True, default="")

    source = models.CharField(
        max_length=10, choices=HISTORY_SOURCE_CHOICES, default="manual",
    )

    remarks = models.TextField(blank=True, default="")

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["-created_at", "-id"]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "employee", "cycle"],
                condition=Q(cycle__isnull=False),
                name="unique_company_employee_cycle_rating_history",
            )
        ]
        indexes = [
            models.Index(fields=["company", "financial_year"]),
        ]

    def __str__(self):
        return f"{self.employee_id} {self.rating} ({self.period_label})"
