from __future__ import annotations

from calendar import monthrange
from datetime import date, datetime
from typing import Dict, List, Tuple

from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required
from sqlalchemy import func

from extensions import db
from models import (
    CTCHead,
    DeductionHead,
    EarningHead,
    Employee,
    EmployeeSalaryStructures,
    FrozenSalaryComponent,
    Payroll,
    SalarySlipTemplate,
    SalaryFormula,
)
from routes.auth import permission_required
from routes.payroll import (
    _ess_get_head_id,
    _ess_get_type,
    compute_monthly_deductions_from_frozen_map,
    compute_monthly_earnings_from_frozen_map,
)


resigned_salary_bp = Blueprint(
    "resigned_salary",
    __name__,
    url_prefix="/resigned-salary",
)


def _month_key(d: date) -> str:
    return f"{d.year:04d}-{d.month:02d}"


def _parse_month(value: str) -> date:
    return datetime.strptime(value, "%Y-%m").date().replace(day=1)


def _shift_month(month_start: date, delta: int) -> date:
    month_index = month_start.year * 12 + (month_start.month - 1) + delta
    year, zero_based_month = divmod(month_index, 12)
    return date(year, zero_based_month + 1, 1)


def _month_label(month: str) -> str:
    return datetime.strptime(month, "%Y-%m").strftime("%B %Y")


def _safe_float(value, default=0.0) -> float:
    try:
        number = float(value or 0.0)
    except (TypeError, ValueError):
        return float(default)
    if number < 0:
        return 0.0
    return round(number, 2)


def _current_structure_maps(employee_id: int) -> Tuple[Dict[str, float], Dict[str, float], Dict[str, float]]:
    earnings: Dict[str, float] = {}
    deductions: Dict[str, float] = {}
    ctc: Dict[str, float] = {}

    rows = EmployeeSalaryStructures.query.filter_by(employee_id=employee_id).all()
    for row in rows:
        component_type = (_ess_get_type(row) or "").strip().lower()
        head_id = _ess_get_head_id(row)
        amount = _safe_float(getattr(row, "amount", 0.0))

        if component_type == "earning":
            head = EarningHead.query.get(head_id)
            target = earnings
        elif component_type == "deduction":
            head = DeductionHead.query.get(head_id)
            target = deductions
        elif component_type == "ctc":
            head = CTCHead.query.get(head_id)
            target = ctc
        else:
            continue

        if head and head.name:
            target[head.name] = round(target.get(head.name, 0.0) + amount, 2)

    return earnings, deductions, ctc


def _frozen_map_for_month(employee_id: int, month: str):
    rows = FrozenSalaryComponent.query.filter_by(employee_id=employee_id, month=month).all()
    if not rows:
        return None

    result = {"earning": {}, "deduction": {}, "ctc": {}}
    for row in rows:
        component_type = (row.component_type or "").strip().lower()
        if component_type not in result:
            continue
        head = (row.head_name or "").strip()
        if not head:
            continue
        result[component_type][head] = round(
            result[component_type].get(head, 0.0) + _safe_float(row.amount),
            2,
        )

    # A useful salary snapshot must at least contain earnings.
    return result if result["earning"] else None



def _latest_component_map_on_or_before(employee_id: int, month: str, component_type: str):
    """Return the latest frozen map for one component type on/before month.

    Historical payrolls can contain a valid earning snapshot but no frozen
    deduction rows (for example older payroll runs created before deduction
    freezing was introduced).  Resigned Salary/F&F must therefore resolve
    deductions independently instead of assuming the earning snapshot month
    also contains every deduction head.
    """
    component_type = (component_type or "").strip().lower()
    if component_type not in {"earning", "deduction", "ctc"}:
        return {}, None

    latest_month = (
        db.session.query(func.max(FrozenSalaryComponent.month))
        .filter(FrozenSalaryComponent.employee_id == employee_id)
        .filter(FrozenSalaryComponent.component_type == component_type)
        .filter(FrozenSalaryComponent.month <= month)
        .scalar()
    )
    if not latest_month:
        return {}, None

    rows = FrozenSalaryComponent.query.filter_by(
        employee_id=employee_id,
        month=latest_month,
        component_type=component_type,
    ).all()

    out = {}
    for row in rows:
        head = (row.head_name or "").strip()
        if not head:
            continue
        out[head] = round(out.get(head, 0.0) + _safe_float(row.amount), 2)
    return out, latest_month


def _resolved_deduction_map(employee_id: int, month: str, exact_snapshot: dict | None):
    """Resolve deduction heads for the resigned salary document.

    Priority:
      1. Exact frozen deduction snapshot for the selected month.
      2. Latest frozen deduction snapshot on/before that month.
      3. Current assigned deduction structure as a final fallback.

    This keeps historical deductions visible even where the old frozen record
    contains only earning components.
    """
    exact = (exact_snapshot or {}).get("deduction") or {}
    if exact:
        return dict(exact), month, "Exact frozen deduction snapshot"

    frozen, frozen_month = _latest_component_map_on_or_before(employee_id, month, "deduction")
    if frozen:
        return frozen, frozen_month, "Historical frozen deduction snapshot"

    _earnings, current_deductions, _ctc = _current_structure_maps(employee_id)
    if current_deductions:
        return current_deductions, None, "Current assigned deduction structure"

    # Some older employees have no deduction rows in FrozenSalaryComponent and
    # no explicit EmployeeSalaryStructures deduction row, even though statutory
    # deduction heads/formulas (PF/ESI etc.) are configured globally.  Build a
    # zero-valued map from configured deduction formulas so the normal payroll
    # deduction calculator can evaluate those heads from monthly earnings.
    formula_heads = (
        db.session.query(DeductionHead)
        .join(SalaryFormula, SalaryFormula.component_id == DeductionHead.id)
        .filter(SalaryFormula.component_type == "deduction")
        .all()
    )
    configured = {
        head.name: 0.0
        for head in formula_heads
        if head and (head.name or "").strip()
    }
    if configured:
        return configured, None, "Configured deduction formula(s)"

    return {}, None, "No deduction structure found"

def _latest_snapshot_on_or_before(employee_id: int, month: str):
    latest_month = (
        db.session.query(func.max(FrozenSalaryComponent.month))
        .filter(FrozenSalaryComponent.employee_id == employee_id)
        .filter(FrozenSalaryComponent.component_type == "earning")
        .filter(FrozenSalaryComponent.month <= month)
        .scalar()
    )
    if latest_month:
        snapshot = _frozen_map_for_month(employee_id, latest_month)
        if snapshot:
            return snapshot, latest_month, "Historical frozen salary"

    earnings, deductions, ctc = _current_structure_maps(employee_id)
    return (
        {"earning": earnings, "deduction": deductions, "ctc": ctc},
        None,
        "Current assigned salary structure (historical snapshot unavailable)",
    )


def _last_drawn_gross(employee: Employee) -> Tuple[float, str, str]:
    lwd_month = _month_key(employee.exit_date)
    snapshot, source_month, source_label = _latest_snapshot_on_or_before(employee.id, lwd_month)
    gross = round(sum((snapshot.get("earning") or {}).values()), 2)
    return gross, (source_month or lwd_month), source_label


def _eligible_months(employee: Employee, end_month: date, period_type: str) -> List[date]:
    count = 3 if period_type == "three" else 1
    requested = [_shift_month(end_month, offset) for offset in range(-(count - 1), 1)]

    doj = employee.date_of_joining
    exit_date = employee.exit_date
    eligible = []
    for month_start in requested:
        month_end = date(month_start.year, month_start.month, monthrange(month_start.year, month_start.month)[1])
        if doj and doj > month_end:
            continue
        if exit_date and exit_date < month_start:
            continue
        eligible.append(month_start)
    return eligible


def _build_document(employee: Employee, period_type: str, end_month: date):
    last_drawn_gross, cap_source_month, cap_source_label = _last_drawn_gross(employee)
    months = []

    for month_start in _eligible_months(employee, end_month, period_type):
        month = _month_key(month_start)
        days_in_month = monthrange(month_start.year, month_start.month)[1]
        month_end = date(month_start.year, month_start.month, days_in_month)

        from_date = month_start
        to_date = month_end
        if employee.date_of_joining and employee.date_of_joining > from_date:
            from_date = employee.date_of_joining
        if employee.exit_date and employee.exit_date < to_date:
            to_date = employee.exit_date

        eligible_days = max((to_date - from_date).days + 1, 0) if from_date <= to_date else 0

        exact_snapshot = _frozen_map_for_month(employee.id, month)
        if exact_snapshot:
            snapshot = exact_snapshot
            snapshot_month = month
            snapshot_source = "Exact frozen salary snapshot"
        else:
            snapshot, snapshot_month, snapshot_source = _latest_snapshot_on_or_before(employee.id, month)

        earnings_map = snapshot.get("earning") or {}
        ctc_map = snapshot.get("ctc") or {}

        # Resolve deductions independently from earnings. Older frozen salary
        # snapshots can legitimately contain earnings while deduction rows are
        # absent. In that case use the latest historical deduction snapshot,
        # then the employee's assigned deduction structure as a fallback.
        deductions_map, deduction_snapshot_month, deduction_snapshot_source = _resolved_deduction_map(
            employee.id, month, exact_snapshot
        )

        earnings, gross = compute_monthly_earnings_from_frozen_map(
            earnings_map,
            eligible_days,
            days_in_month,
        )

        # If this month was already processed in normal payroll, use its final
        # deduction total for reconciliation. This preserves one-off/loan/statutory
        # deductions while still showing the component-wise breakup.
        payroll_row = Payroll.query.filter_by(employee_id=employee.id, month=month).first()
        payroll_deduction_total = (
            float(getattr(payroll_row, "deductions", 0.0) or 0.0)
            if payroll_row is not None
            else None
        )

        deductions, total_deductions = compute_monthly_deductions_from_frozen_map(
            deductions_map,
            eligible_days,
            days_in_month,
            payroll_total=payroll_deduction_total,
            monthly_gross=gross,
            monthly_earnings_map=earnings,
        )

        # Very old payroll rows may have only the final deduction total and no
        # frozen/component structure at all. Do not show a misleading zero in
        # the resigned salary document; preserve the processed amount as an
        # Other Deduction fallback.
        if (not deductions) and payroll_deduction_total is not None and payroll_deduction_total > 0:
            deductions = {"Other Deduction": round(payroll_deduction_total, 2)}
            total_deductions = round(payroll_deduction_total, 2)
            deduction_snapshot_source = "Processed payroll deduction total (component breakup unavailable)"
            deduction_snapshot_month = month

        # A generated settlement month can never be above last-drawn master gross.
        # Normally this only guards against an inconsistent historical structure.
        if last_drawn_gross > 0 and gross > last_drawn_gross:
            factor = last_drawn_gross / gross
            earnings = {name: round(amount * factor, 2) for name, amount in earnings.items()}
            gross = round(sum(earnings.values()), 2)

        months.append(
            {
                "month": month,
                "month_label": _month_label(month),
                "from_date": from_date,
                "to_date": to_date,
                "eligible_days": eligible_days,
                "days_in_month": days_in_month,
                "snapshot_month": snapshot_month,
                "snapshot_source": snapshot_source,
                "deduction_snapshot_month": deduction_snapshot_month,
                "deduction_snapshot_source": deduction_snapshot_source,
                "earnings": [{"name": k, "amount": round(v, 2)} for k, v in earnings.items()],
                "deductions": [{"name": k, "amount": round(v, 2)} for k, v in deductions.items()],
                "ctc": [{"name": k, "amount": round(v, 2)} for k, v in ctc_map.items()],
                "gross": round(gross, 2),
                "total_deductions": round(total_deductions, 2),
                "net": round(gross - total_deductions, 2),
            }
        )

    return {
        "employee": employee,
        "period_type": period_type,
        "end_month": _month_key(end_month),
        "months": months,
        "last_drawn_gross": last_drawn_gross,
        "cap_source_month": cap_source_month,
        "cap_source_label": cap_source_label,
    }


def _apply_posted_amounts(document):
    errors = []

    for month_row in document["months"]:
        token = month_row["month"].replace("-", "_")

        for prefix, bucket in (("earning", "earnings"), ("deduction", "deductions"), ("ctc", "ctc")):
            updated = []
            index = 0
            while True:
                name_key = f"{prefix}_name_{token}_{index}"
                amount_key = f"{prefix}_amount_{token}_{index}"
                if name_key not in request.form:
                    break
                name = (request.form.get(name_key) or "").strip()
                if name:
                    updated.append({"name": name, "amount": _safe_float(request.form.get(amount_key))})
                index += 1
            if updated or any(k.startswith(f"{prefix}_name_{token}_") for k in request.form.keys()):
                month_row[bucket] = updated

        month_row["gross"] = round(sum(x["amount"] for x in month_row["earnings"]), 2)
        month_row["total_deductions"] = round(sum(x["amount"] for x in month_row["deductions"]), 2)
        month_row["net"] = round(month_row["gross"] - month_row["total_deductions"], 2)

        cap = round(float(document["last_drawn_gross"] or 0.0), 2)
        if cap > 0 and month_row["gross"] > cap + 0.009:
            errors.append(
                f"{month_row['month_label']}: Gross salary Rs. {month_row['gross']:,.2f} "
                f"cannot exceed last drawn gross Rs. {cap:,.2f}."
            )

    return errors


def _resolved_slip_template(employee: Employee):
    # Reuse company identity from the configured salary-slip template where available.
    candidates = SalarySlipTemplate.query.filter_by(is_active=True).all()
    best = None
    best_score = -1
    for tpl in candidates:
        scope = (tpl.scope_type or "global").lower()
        score = 0
        if scope == "global":
            score = 1
        elif scope == "location" and tpl.location == employee.location:
            score = 2
        elif scope == "institute" and tpl.institute == employee.institute:
            score = 2
        elif scope == "location_institute" and tpl.location == employee.location and tpl.institute == employee.institute:
            score = 3
        else:
            continue
        if score > best_score:
            best = tpl
            best_score = score
    return best


@resigned_salary_bp.route("/", methods=["GET", "POST"])
@login_required
@permission_required("resigned_salary.index")
def index():
    employees = (
        Employee.query
        .filter(Employee.exit_date.isnot(None))
        .filter(Employee.exit_date <= date.today())
        .order_by(Employee.exit_date.desc(), Employee.full_name.asc())
        .all()
    )

    document = None
    finalized = False

    if request.method == "POST":
        employee_id = request.form.get("employee_id", type=int)
        period_type = (request.form.get("period_type") or "single").strip().lower()
        end_month_raw = (request.form.get("end_month") or "").strip()
        stage = (request.form.get("stage") or "preview").strip().lower()

        if period_type not in {"single", "three"}:
            flash("Please choose Single Month Salary or 3 Month F&F.", "danger")
            return redirect(url_for("resigned_salary.index"))

        employee = Employee.query.get(employee_id) if employee_id else None
        if not employee or not employee.exit_date:
            flash("Please select a resigned employee with a recorded last working date.", "danger")
            return redirect(url_for("resigned_salary.index"))

        try:
            end_month = _parse_month(end_month_raw)
        except (TypeError, ValueError):
            flash("Please select a valid salary month.", "danger")
            return redirect(url_for("resigned_salary.index"))

        lwd_month = employee.exit_date.replace(day=1)
        if end_month > lwd_month:
            flash(
                f"Salary/F&F cannot be generated after the employee's last working month "
                f"({_month_label(_month_key(lwd_month))}).",
                "danger",
            )
            return redirect(url_for("resigned_salary.index"))

        if employee.date_of_joining and end_month < employee.date_of_joining.replace(day=1):
            flash("The selected month is before the employee's date of joining.", "danger")
            return redirect(url_for("resigned_salary.index"))

        document = _build_document(employee, period_type, end_month)
        if not document["months"]:
            flash("No eligible employment period exists for the selected month(s).", "danger")
            return redirect(url_for("resigned_salary.index"))

        if stage == "finalize":
            errors = _apply_posted_amounts(document)
            if errors:
                for error in errors:
                    flash(error, "danger")
            else:
                finalized = True
                flash("Salary/F&F document validated successfully. It is ready to print or save as PDF.", "success")

    selected_employee = document["employee"] if document else None
    slip_template = _resolved_slip_template(selected_employee) if selected_employee else None

    return render_template(
        "resigned_salary/index.html",
        employees=employees,
        document=document,
        finalized=finalized,
        slip_template=slip_template,
        today=date.today(),
    )
