# ============================================================
# ADDITIVE: Training / "Learning & Skill Matrix Development"
#
# Nothing existing is modified or duplicated:
#   * employees        -> Employee.EmployeeDT         (FK)
#   * manager / HOD    -> Employee.ReportingHierarchy (read only, for nomination approvals)
#   * audit fields     -> People.models.Audit         (abstract, same convention)
# Screens covered:
#   Dashboard / Programs / Calendar / Enrollment / Attendance / Certificates / Skill Matrix
# ============================================================
from decimal import Decimal

from django.db import models
from django.utils import timezone

from Company.models import company_details
from Employee.models import Department, EmployeeDT
from People.models import Audit

SKILL_LEVELS = {0: "None", 1: "Novice", 2: "Intermediate", 3: "Practitioner", 4: "Expert"}


class TrainingSkill(Audit):
    """A row of the Skill Competency Matrix (domain + proficiency target)."""
    GAP = [("Optimal", "Optimal"), ("Active Track", "Active Track"), ("Upskilling", "Upskilling"),
           ("Critical", "Critical")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="training_skills")
    domain = models.CharField(max_length=200)                       # "Kubernetes & Microservices"
    category = models.CharField(max_length=80, blank=True, null=True)   # Engineering / Leadership ...
    description = models.TextField(blank=True, null=True)
    target_level = models.PositiveSmallIntegerField(default=3)      # 1..4
    department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True,
                                   related_name="+")                # scope of the bench (empty = whole company)
    gap_level_override = models.CharField(max_length=14, choices=GAP, blank=True, null=True)

    class Meta:
        ordering = ["domain"]
        unique_together = (("company", "domain"),)


class TrainingProgram(Audit):
    STATUS = [("Draft", "Draft"), ("Upcoming", "Upcoming"), ("Ongoing", "Ongoing"),
              ("Completed", "Completed"), ("Cancelled", "Cancelled")]
    MODE = [("Classroom", "Classroom"), ("Online", "Online"), ("Hybrid", "Hybrid"), ("Self-paced", "Self-paced")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="training_programs")
    code = models.CharField(max_length=20)                           # TRN-01
    title = models.CharField(max_length=250)
    description = models.TextField(blank=True, null=True)
    category = models.CharField(max_length=80, blank=True, null=True)   # Technical / Leadership / Compliance
    trainer_name = models.CharField(max_length=150, blank=True, null=True)   # "External Specialist"
    trainer = models.ForeignKey(EmployeeDT, on_delete=models.SET_NULL, null=True, blank=True,
                                related_name="trainings_conducted")
    mode = models.CharField(max_length=12, choices=MODE, default="Classroom")
    duration_hours = models.DecimalField(max_digits=6, decimal_places=1, default=Decimal("0"))
    capacity = models.PositiveIntegerField(null=True, blank=True)
    audience_label = models.CharField(max_length=40, default="Employees")    # "24 Engineers"
    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)
    status = models.CharField(max_length=10, choices=STATUS, default="Upcoming", db_index=True)
    is_mandatory = models.BooleanField(default=False)
    awards_certificate = models.BooleanField(default=True)
    certificate_title = models.CharField(max_length=250, blank=True, null=True)  # "Kubernetes Master Certificate"
    certificate_validity_months = models.PositiveIntegerField(null=True, blank=True)
    pass_attendance_percent = models.PositiveSmallIntegerField(default=75)
    skills = models.ManyToManyField(TrainingSkill, blank=True, related_name="programs")
    skill_level_awarded = models.PositiveSmallIntegerField(default=0)   # 0 = do not touch skill levels

    class Meta:
        ordering = ["code"]
        unique_together = (("company", "code"),)


class TrainingSession(Audit):
    STATUS = [("Scheduled", "Scheduled"), ("Completed", "Completed"), ("Cancelled", "Cancelled")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="training_sessions")
    program = models.ForeignKey(TrainingProgram, on_delete=models.CASCADE, related_name="sessions")
    title = models.CharField(max_length=250)
    session_date = models.DateField(db_index=True)
    start_time = models.TimeField(null=True, blank=True)
    end_time = models.TimeField(null=True, blank=True)
    location = models.CharField(max_length=200, blank=True, null=True)    # "Pune Tech HQ Lab 2"
    meeting_link = models.URLField(blank=True, null=True)
    trainer_name = models.CharField(max_length=150, blank=True, null=True)
    status = models.CharField(max_length=10, choices=STATUS, default="Scheduled", db_index=True)
    notes = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["session_date", "start_time", "id"]

    @property
    def hours(self):
        if self.start_time and self.end_time:
            a = self.start_time.hour * 60 + self.start_time.minute
            b = self.end_time.hour * 60 + self.end_time.minute
            return Decimal(max(b - a, 0)) / Decimal(60)
        return Decimal("0")


class TrainingEnrollment(Audit):
    STATUS = [("Pending", "Pending Approval"), ("Enrolled", "Enrolled"), ("Completed", "Completed"),
              ("Rejected", "Rejected"), ("Dropped", "Dropped"), ("Cancelled", "Cancelled")]
    SOURCE = [("Self", "Self nomination"), ("Manager", "Manager nomination"), ("HR", "HR enrolment")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="training_enrollments")
    program = models.ForeignKey(TrainingProgram, on_delete=models.CASCADE, related_name="enrollments")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="training_enrollments")
    status = models.CharField(max_length=10, choices=STATUS, default="Pending", db_index=True)
    source = models.CharField(max_length=8, choices=SOURCE, default="HR")
    nominated_by = models.CharField(max_length=150, blank=True, null=True)
    reason = models.TextField(blank=True, null=True)
    approver_code = models.CharField(max_length=100, blank=True, null=True, db_index=True)
    decided_by = models.CharField(max_length=150, blank=True, null=True)
    decided_at = models.DateTimeField(null=True, blank=True)
    decision_remarks = models.TextField(blank=True, null=True)
    completed_on = models.DateField(null=True, blank=True)
    score = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    feedback_rating = models.DecimalField(max_digits=2, decimal_places=1, null=True, blank=True)
    feedback_comment = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["-id"]
        indexes = [models.Index(fields=["company", "status"]), models.Index(fields=["company", "approver_code", "status"])]


class TrainingAttendance(Audit):
    STATUS = [("Present", "Present"), ("Late", "Late"), ("Absent", "Absent"), ("Excused", "Excused")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="training_attendance")
    session = models.ForeignKey(TrainingSession, on_delete=models.CASCADE, related_name="attendance")
    enrollment = models.ForeignKey(TrainingEnrollment, on_delete=models.CASCADE, related_name="attendance")
    status = models.CharField(max_length=8, choices=STATUS, default="Present", db_index=True)
    hours_attended = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0"))
    remarks = models.CharField(max_length=250, blank=True, null=True)
    marked_by = models.CharField(max_length=150, blank=True, null=True)

    class Meta:
        ordering = ["session__session_date", "id"]
        unique_together = (("session", "enrollment"),)


class TrainingCertificate(Audit):
    STATUS = [("Issued", "Issued"), ("Revoked", "Revoked")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="training_certificates")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="training_certificates")
    program = models.ForeignKey(TrainingProgram, on_delete=models.SET_NULL, null=True, blank=True,
                                related_name="certificates")
    enrollment = models.ForeignKey(TrainingEnrollment, on_delete=models.SET_NULL, null=True, blank=True,
                                   related_name="certificates")
    certificate_no = models.CharField(max_length=40)
    verification_code = models.CharField(max_length=24, db_index=True)
    title = models.CharField(max_length=250)
    issued_on = models.DateField(default=timezone.localdate)
    expiry_date = models.DateField(null=True, blank=True)
    issued_by = models.CharField(max_length=150, blank=True, null=True)
    status = models.CharField(max_length=8, choices=STATUS, default="Issued", db_index=True)
    is_external = models.BooleanField(default=False)          # uploaded third-party certificate
    issuer_name = models.CharField(max_length=200, blank=True, null=True)
    file = models.FileField(upload_to="training_certificates/", null=True, blank=True)

    class Meta:
        ordering = ["-issued_on", "-id"]
        unique_together = (("company", "certificate_no"),)


class EmployeeSkill(Audit):
    SOURCE = [("Manual", "HR / Manager assessment"), ("Self", "Self assessment"), ("Training", "Training completion")]
    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="employee_skills")
    employee = models.ForeignKey(EmployeeDT, on_delete=models.CASCADE, related_name="skill_levels")
    skill = models.ForeignKey(TrainingSkill, on_delete=models.CASCADE, related_name="ratings")
    current_level = models.PositiveSmallIntegerField(default=0)       # 0..4
    assessed_on = models.DateField(default=timezone.localdate)
    assessed_by = models.CharField(max_length=150, blank=True, null=True)
    source = models.CharField(max_length=8, choices=SOURCE, default="Manual")
    remarks = models.CharField(max_length=250, blank=True, null=True)

    class Meta:
        ordering = ["skill__domain", "employee__name"]
        unique_together = (("employee", "skill"),)
