from __future__ import annotations

from decimal import Decimal

from sqlalchemy.orm import Session

from app.models.master_data import ReportBudgetAllocation


DEFAULT_REPORT_ALLOCATIONS = (
    ("Administrative", "NON_PLAN_MV", "Non-Plan M.V", "150000000"),
    ("Administrative", "EQUIP_MACH", "Equip. & Mach.", "40217428"),
    ("Administrative", "COMM_UP", "Com. Up.", "3220705"),
    ("Administrative", "TRAINING_EQUIP", "Training Equip.", "15815190"),
    ("Administrative", "TRG_COMM_UP_GRD", "Trg. Com. Up Grd.", "2200000"),
    ("Administrative", "NON_PLAN_OC", "Non-Plan O.C", "16996305"),
    ("Administrative", "COMPUTER_CONSUMABLE", "Computer Consumable", "53500"),
    ("Administrative", "COMPUTER_SPARE_SERVICE", "Computer Spare & Service", "38850"),
    ("Programme", "FP_C", "Equip. & Mach. (FP&C)", "7224842"),
    ("Programme", "SCPSC", "Equip. & Mach. (SCPSC)", "3143818"),
    ("Programme", "TASP", "Equip. & Mach. (TASP)", "3406901"),
)


def upsert_default_report_allocations(db: Session, financial_year: str = "2026-27") -> int:
    """Load the initial balances from the 20-08-2026 reference status report."""

    changed = 0
    for group, code, name, amount in DEFAULT_REPORT_ALLOCATIONS:
        row = (
            db.query(ReportBudgetAllocation)
            .filter(
                ReportBudgetAllocation.financial_year == financial_year,
                ReportBudgetAllocation.expenditure_group == group,
                ReportBudgetAllocation.head_code == code,
            )
            .first()
        )
        if row is None:
            db.add(
                ReportBudgetAllocation(
                    financial_year=financial_year,
                    expenditure_group=group,
                    head_code=code,
                    head_name=name,
                    allocation_amount=Decimal(amount),
                    remarks="Opening balance from Procurement Status dated 20.08.2026",
                )
            )
            changed += 1
    return changed
