# ============================================================
# ADDITIVE: HR MIS & Workforce Analytics (Reports & MIS) - models
# ------------------------------------------------------------
# The 9 report tabs are COMPUTED from data that already exists
# (EmployeeDT, Payroll, AttendanceEmp / EMP_check_in_check_out,
# LeaveRequest + leave balances, Recruitment candidates / offers,
# Training programs / enrolments / certificates, Perf* ratings,
# ExitClearance / ExitInterview). Nothing is copied into new tables.
#
# DUPLICATE CHECK - every existing model was reviewed:
#   no Report / MIS / Benchmark / Export-history model existed.
#   Company.views dashboard (headcount card) is a live widget, not a report store.
#   Company/utils_payroll_export.py is the payroll sheet exporter - untouched.
#
# Only data that is CONFIGURATION or HISTORY and not derivable gets a table:
#   ReportBenchmark   targets used by the cards (industry attrition 14%, office start
#                     time for punctuality, annual payroll budget per financial year ...)
#   ExitReasonGroup   how exit-interview reasons are grouped on the Exit Reports tab,
#                     with the HR judgement "Preventable %" and "Key Retention
#                     Recommendation" (not derivable from data)
#   ReportExport      history of "Export Employee Master" / "Export Recruitment Data"
#                     files (who, when, filters, rows, the file itself)
#
# Imported at the bottom of People/models.py (one additive line).
# ============================================================

from django.db import models

from Company.models import company_details

from .models import Audit

__all__ = ["ReportBenchmark", "ExitReasonGroup", "ReportExport"]


class ReportBenchmark(Audit):
    """key/value targets used by the report cards. financial_year '' = applies to every year."""

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_report_benchmarks")
    key = models.CharField(max_length=60)                       # industry_attrition_percent
    label = models.CharField(max_length=150, blank=True, null=True)
    value = models.DecimalField(max_digits=16, decimal_places=2)
    unit = models.CharField(max_length=20, blank=True, null=True)   # % | INR | minutes | days
    financial_year = models.CharField(max_length=9, blank=True, default="")   # 2026-27
    notes = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["key", "-financial_year"]
        unique_together = (("company", "key", "financial_year"),)


class ExitReasonGroup(Audit):
    """A row of 'Annual Attrition Drivers & Reason Analysis'."""

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_exit_reason_groups")
    name = models.CharField(max_length=120)                     # Higher Education / Relocation
    reasons = models.JSONField(default=list, blank=True)        # ExitInterview.reason_for_leaving values
    preventable_percent = models.DecimalField(max_digits=5, decimal_places=2, default=0)
    recommendation = models.TextField(blank=True, null=True)    # Key Retention Recommendation
    sort_order = models.PositiveSmallIntegerField(default=0)

    class Meta:
        ordering = ["sort_order", "id"]
        unique_together = (("company", "name"),)


class ReportExport(Audit):
    """One generated export file (history + re-download)."""

    TYPES = [("employee_master", "Employee Master"), ("recruitment_data", "Recruitment Data")]
    FORMATS = [("csv", "CSV"), ("xlsx", "Excel (.xlsx)")]
    STATUS = [("Completed", "Completed"), ("Failed", "Failed")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_report_exports")
    report_type = models.CharField(max_length=20, choices=TYPES, db_index=True)
    file_format = models.CharField(max_length=5, choices=FORMATS, default="csv")
    title = models.CharField(max_length=200, blank=True, null=True)
    filters = models.JSONField(default=dict, blank=True)
    row_count = models.PositiveIntegerField(default=0)
    status = models.CharField(max_length=10, choices=STATUS, default="Completed")
    error = models.TextField(blank=True, null=True)
    file = models.FileField(upload_to="report_exports/%Y/%m/", blank=True, null=True)
    file_name = models.CharField(max_length=200, blank=True, null=True)
    file_size = models.PositiveIntegerField(default=0)
    download_count = models.PositiveIntegerField(default=0)
    last_downloaded_at = models.DateTimeField(null=True, blank=True)
    notes = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["-id"]
