import click
from flask import current_app
from flask.cli import with_appcontext
from datetime import date
from extensions import db
from models import Employee, LeaveType, LeaveBalance

@click.command('auto-credit-leaves')
@with_appcontext
def auto_credit_leaves():
    today = date.today()
    fiscal_start = date(today.year, 4, 1)  # FY assumed Apr 1 - Mar 31

    fy_year = today.year if today >= fiscal_start else today.year - 1
    fy_start = date(fy_year, 4, 1)
    fy_end = date(fy_year + 1, 3, 31)

    leave_types = LeaveType.query.all()
    employees = Employee.query.filter_by(status='active').all()

    click.echo(f"🚀 Starting auto-credit leaves for FY {fy_year}-{fy_year +1} as of {today}...")

    for emp in employees:
        for lt in leave_types:
            balance = LeaveBalance.query.filter_by(employee_id=emp.id, leave_type_id=lt.id, year=fy_year).first()
            if not balance:
                balance = LeaveBalance(employee_id=emp.id, leave_type_id=lt.id, balance=0, year=fy_year)
                db.session.add(balance)
                db.session.flush()

            doj = emp.date_of_joining
            months = 12
            if lt.pro_rata and doj > fy_start:
                # calculate months worked in FY
                months = max(1, 12 - (doj.month - 4 + (0 if doj.day == 1 else 1)))
                if doj.month < 4:
                    months = 12

            # 1️⃣ MONTHLY CREDIT TYPES
            if lt.monthly_credit:
                monthly_amount = round(lt.annual_quota / 12, 2)
                balance.balance += monthly_amount
                click.echo(f"  ➤ {emp.full_name} ({lt.code}): +{monthly_amount} monthly credit")

            # 2️⃣ FY ANNUAL CREDIT TYPES (no monthly_credit, but has annual_quota)
            if not lt.monthly_credit and lt.annual_quota > 0:
                if balance.balance == 0:  # ensure only once
                    annual_amount = round((lt.annual_quota / 12) * months, 2) if lt.pro_rata else lt.annual_quota
                    balance.balance += annual_amount
                    click.echo(f"  ➤ {emp.full_name} ({lt.code}): +{annual_amount} annual FY credit (pro-rata {months} months)")

    db.session.commit()
    click.echo("✅ Auto-credit leaves completed.")