# ============================================================
# ADDITIVE: Daily attendance auto-marking scheduler.
#
# Ported from the legacy MVT project's Company/views.py
# (Attendance() + scheduled_task()), adapted to:
#   - real field names already in Employee/models.py
#   - the project's own Holiday model instead of the pypi
#     `holidays` package, so HR's own holiday list (see
#     HolidayViewSet) is what actually drives "Holiday" status,
#     company by company.
#
# Nothing existing is touched - this is a new file, wired in
# from Company/apps.py's ready().
# ============================================================

import os
import sys
from datetime import datetime, timedelta

from django.db import transaction
from django.utils import timezone

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger

timezone.activate("Asia/Kolkata")

_scheduler = BackgroundScheduler(timezone="Asia/Kolkata")


@transaction.atomic
def mark_daily_attendance():
    """
    Mark yesterday's attendance for every active employee, across
    every company, based on their EMP_check_in_check_out records
    and their company's own Holiday list.
    """

    from Company.models import Holiday
    from Employee.models import EmployeeDT, EMP_check_in_check_out, AttendanceEmp

    today = timezone.localdate()
    yesterday = today - timedelta(days=1)

    LEAVE_STATUSES = {"Paid Leave", "Sick Leave", "Casual Leave"}

    for employee in EmployeeDT.objects.filter(is_active=True).select_related("company"):

        # Already marked? Don't double-create.
        if AttendanceEmp.objects.filter(
            Employee_ID=employee.employee_code, date=yesterday
        ).exists():
            continue

        is_holiday = Holiday.objects.filter(
            company=employee.company, date=yesterday, is_active=True
        ).exists()

        if employee.Work_sift == "Night Shift":
            attendance_record = EMP_check_in_check_out.objects.filter(
                Employee_ID=employee.employee_code,
                login_date=yesterday,
                logout_date=today,
            )
        else:  # Day Shift (default)
            attendance_record = EMP_check_in_check_out.objects.filter(
                Employee_ID=employee.employee_code,
                login_date=yesterday,
                logout_date=yesterday,
            )

        status = None
        comment = None
        total_working_hours = None

        if attendance_record.exists():

            record = attendance_record.order_by("-id").first()

            if record.total_working_hours:

                try:

                    from .utils_payroll_export import time_to_decimal

                    total_work_hours = time_to_decimal(record.total_working_hours)
                    expected_hours = employee.Work_hours or 8

                    # Sunday and holidays are always fully paid, even
                    # on a short day, so only weekdays/Saturday get
                    # the half-day check here.
                    if yesterday.weekday() == 6 or is_holiday:
                        status = "Present"
                    elif total_work_hours < (expected_hours / 2):
                        status = "Half Day"
                    else:
                        status = "Present"

                    total_working_hours = record.total_working_hours
                    comment = record.comment

                except (ValueError, TypeError):
                    pass

        elif is_holiday:

            status = "Holiday"
            comment = "Holiday"

        elif yesterday.weekday() == 6:

            status = "Off"
            comment = "Sunday Off"

        else:

            status = "Absent"
            comment = "Absent"

        AttendanceEmp.objects.create(
            Employee_ID=employee.employee_code,
            company=employee.company,
            Name=employee.name,
            image=employee.image,
            date=yesterday,
            status=status,
            comment=comment,
            total_working_hours=total_working_hours,
        )

        # Clear any stale "still checked in" flag left over from
        # yesterday (mirrors the legacy behaviour).
        if employee.check_st or employee.Employ_check_id:

            employee.check_st = None
            employee.Employ_check_id = None
            employee.save(update_fields=["check_st", "Employ_check_id"])


def run_scheduled_attendance_task():
    """
    Runs mark_daily_attendance() at most once per calendar day,
    tracked via the Attendance_Status singleton row (pk=1) -
    exactly like the legacy scheduled_task().
    """

    from Company.models import Attendance_Status

    today = timezone.localdate()

    task_status, _created = Attendance_Status.objects.get_or_create(pk=1)

    if task_status.last_run_date == today:
        return

    mark_daily_attendance()

    task_status.last_run_date = today
    task_status.save(update_fields=["last_run_date"])


def start_scheduler():
    """
    Start the background scheduler once per process. Guarded so
    Django's autoreloader (which spawns a watcher + a worker
    process under `runserver`) doesn't start it twice.
    """

    if _scheduler.running:
        return

    # Under `manage.py runserver`, Django's autoreloader spawns a
    # parent "watcher" process plus a child worker process; only
    # the child (RUN_MAIN=true) should run the scheduler, or it
    # would fire every job twice. Any other entry point (gunicorn,
    # uwsgi, `runserver --noreload`, tests, etc.) never sets
    # RUN_MAIN at all, so it starts normally there.
    if "runserver" in sys.argv and os.environ.get("RUN_MAIN") != "true":
        return

    _scheduler.add_job(
        run_scheduled_attendance_task,
        CronTrigger(hour=9, minute=50, timezone="Asia/Kolkata"),
        id="attendance_task_0950",
        replace_existing=True,
    )

    _scheduler.add_job(
        run_scheduled_attendance_task,
        CronTrigger(hour=11, minute=31, timezone="Asia/Kolkata"),
        id="attendance_task_1131",
        replace_existing=True,
    )

    _scheduler.start()
 
