from decimal import Decimal, ROUND_HALF_UP
from django.core.exceptions import ValidationError
from django.db import transaction

from apps.accounting.models import Account, AccountingPolicy, Party, Voucher
from apps.accounting.services import PostingRuleEngine, PostingService, VoucherService
from apps.audit.services import record_audit_event
from apps.budgeting.services import BudgetControlService
from .models import (
    PurchaseOrder,
    PurchaseOrderLine,
    PurchaseRequisition,
    PurchaseRequisitionLine,
    QuotationComparison,
    RFQ,
    ThreeWayMatch,
    VendorContact,
    VendorProfile,
    VendorQuotation,
    VendorQuotationLine,
)


def _find_acc(company, role: str, fallback: str) -> Account | None:
    return (
        Account.objects.filter(company=company, control_role=role, is_group=False, is_active=True).first()
        or Account.objects.filter(company=company, code__startswith=fallback, is_group=False, is_active=True).first()
    )


class ProcurementService:
    @staticmethod
    @transaction.atomic
    def register_vendor(*, company, user, party_data: dict, vendor_data: dict) -> VendorProfile:
        party, _ = Party.objects.get_or_create(
            company=company,
            code=party_data["code"],
            defaults={
                "party_type": party_data.get("party_type", Party.PartyType.SUPPLIER),
                "name": party_data["name"],
                "pan_vat_no": vendor_data.get("pan_vat_no", party_data.get("pan_vat_no", "")),
                "phone": party_data.get("phone", ""),
                "email": party_data.get("email", ""),
                "address": party_data.get("address", ""),
                "credit_limit": Decimal(str(party_data.get("credit_limit") or "0.00")),
                "payment_terms_days": int(party_data.get("payment_terms_days") or 30),
                "control_account": _find_acc(company, Account.ControlRole.SUNDRY_CREDITORS, "201"),
            },
        )
        vp = VendorProfile(
            company=company,
            party=party,
            vendor_category=vendor_data.get("vendor_category", VendorProfile.Category.MATERIALS),
            registration_no=vendor_data.get("registration_no", ""),
            pan_vat_no=vendor_data.get("pan_vat_no", party.pan_vat_no),
            bank_name=vendor_data.get("bank_name", ""),
            bank_account_no=vendor_data.get("bank_account_no", ""),
            bank_branch=vendor_data.get("bank_branch", ""),
            status=vendor_data.get("status", VendorProfile.Status.PENDING),
        )
        vp.full_clean()
        vp.save()
        for c in vendor_data.get("contacts") or []:
            VendorContact.objects.create(vendor=vp, **c)
        record_audit_event(
            company=company, actor=user, action="VENDOR_REGISTERED", entity_type="VendorProfile",
            entity_id=str(vp.id), new_state={"code": party.code, "pan": vp.pan_vat_no},
        )
        return vp

    @staticmethod
    @transaction.atomic
    def create_requisition(*, company, user, data: dict, lines_data: list[dict]) -> PurchaseRequisition:
        req = PurchaseRequisition.objects.create(
            company=company,
            requisition_no=data["requisition_no"],
            requisition_date=data["requisition_date"],
            required_delivery_date=data["required_delivery_date"],
            department=data.get("department"),
            project=data["project"],
            site=data.get("site"),
            priority=data.get("priority", "NORMAL"),
            notes=data.get("notes", ""),
            requested_by=user,
        )
        warnings = []
        for row in lines_data:
            qty = Decimal(str(row["requested_qty"]))
            rate = Decimal(str(row.get("estimated_rate") or "0.00"))
            tot = (qty * rate).quantize(Decimal("0.01"))
            bline = row.get("budget_line")
            if bline:
                ok, w = BudgetControlService.check_availability(company=company, budget_line=bline, amount=tot)
                if not ok and w:
                    warnings.append(w)
            PurchaseRequisitionLine.objects.create(
                requisition=req,
                item=row.get("item"),
                description=row["description"],
                unit=row.get("unit", "Units"),
                requested_qty=qty,
                estimated_rate=rate,
                estimated_total=tot,
                cost_code=row.get("cost_code"),
                budget_line=bline,
            )
        if warnings:
            req.budget_warning = "; ".join(warnings)[:255]
            req.save(update_fields=["budget_warning"])
        return req

    @staticmethod
    @transaction.atomic
    def approve_requisition(*, requisition: PurchaseRequisition, user, allow_override: bool = False) -> PurchaseRequisition:
        requisition = PurchaseRequisition.objects.select_for_update().get(pk=requisition.pk)
        for line in requisition.lines.select_related("budget_line"):
            if line.budget_line:
                BudgetControlService.check_availability(
                    company=requisition.company, budget_line=line.budget_line,
                    amount=line.estimated_total, allow_override=allow_override,
                )
        requisition.status = PurchaseRequisition.Status.APPROVED
        requisition.approved_by = user
        requisition.save(update_fields=["status", "approved_by"])
        return requisition

    @staticmethod
    @transaction.atomic
    def submit_quotation(*, company, rfq: RFQ, vendor: VendorProfile, data: dict, lines_data: list[dict]) -> VendorQuotation:
        sub = Decimal("0.00")
        vq = VendorQuotation.objects.create(
            company=company,
            rfq=rfq,
            vendor=vendor,
            quotation_ref=data["quotation_ref"],
            quoted_date=data["quoted_date"],
            delivery_days=int(data.get("delivery_days") or 7),
            payment_terms_days=int(data.get("payment_terms_days") or 30),
            freight_charge=Decimal(str(data.get("freight_charge") or "0.00")),
            tax_amount=Decimal(str(data.get("tax_amount") or "0.00")),
            discount_amount=Decimal(str(data.get("discount_amount") or "0.00")),
            technical_compliant=bool(data.get("technical_compliant", True)),
            warranty_months=int(data.get("warranty_months") or 0),
        )
        for row in lines_data:
            qty = Decimal(str(row["quantity"]))
            rate = Decimal(str(row["unit_rate"]))
            ltot = (qty * rate).quantize(Decimal("0.01"))
            sub += ltot
            VendorQuotationLine.objects.create(
                quotation=vq,
                item=row.get("item"),
                description=row["description"],
                quantity=qty,
                unit_rate=rate,
                line_total=ltot,
            )
        vq.subtotal_amount = sub
        vq.total_landed_cost = (sub + vq.freight_charge + vq.tax_amount - vq.discount_amount).quantize(Decimal("0.01"))
        vq.save(update_fields=["subtotal_amount", "total_landed_cost"])
        return vq

    @staticmethod
    @transaction.atomic
    def select_quotation(*, company, rfq: RFQ, recommended_vendor: VendorProfile, justification: str, user) -> QuotationComparison:
        rfq.quotations.update(is_selected=False)
        rfq.quotations.filter(vendor=recommended_vendor).update(is_selected=True)
        rfq.status = RFQ.Status.AWARDED
        rfq.save(update_fields=["status"])
        comp, _ = QuotationComparison.objects.update_or_create(
            rfq=rfq,
            defaults={
                "company": company,
                "recommended_vendor": recommended_vendor,
                "justification": justification,
                "compared_by": user,
            },
        )
        return comp

    @staticmethod
    @transaction.atomic
    def create_purchase_order(*, company, user, data: dict, lines_data: list[dict]) -> PurchaseOrder:
        po = PurchaseOrder.objects.create(
            company=company,
            po_number=data["po_number"],
            po_date=data["po_date"],
            order_kind=data.get("order_kind", PurchaseOrder.OrderKind.PROJECT),
            vendor=data["vendor"],
            requisition=data.get("requisition"),
            rfq=data.get("rfq"),
            project=data.get("project"),
            site=data.get("site"),
            payment_terms_days=int(data.get("payment_terms_days") or 30),
            justification=data.get("justification", ""),
            created_by=user,
        )
        sub = Decimal("0.00")
        tax = Decimal("0.00")
        for row in lines_data:
            qty = Decimal(str(row["ordered_qty"]))
            rate = Decimal(str(row["unit_rate"]))
            trate = Decimal(str(row.get("tax_rate") or "13.00"))
            ltot = (qty * rate).quantize(Decimal("0.01"))
            ltax = (ltot * trate / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
            sub += ltot
            tax += ltax
            PurchaseOrderLine.objects.create(
                purchase_order=po,
                item=row.get("item"),
                description=row["description"],
                unit=row.get("unit", "Units"),
                ordered_qty=qty,
                unit_rate=rate,
                tax_rate=trate,
                line_total=ltot,
                cost_code=row.get("cost_code"),
                budget_line=row.get("budget_line"),
            )
        po.subtotal_amount = sub
        po.tax_amount = tax
        po.total_amount = (sub + tax).quantize(Decimal("0.01"))
        po.save(update_fields=["subtotal_amount", "tax_amount", "total_amount"])
        if po.requisition_id:
            po.requisition.status = PurchaseRequisition.Status.CONVERTED
            po.requisition.save(update_fields=["status"])
        return po

    @staticmethod
    @transaction.atomic
    def approve_purchase_order(*, po: PurchaseOrder, user, allow_budget_override: bool = False) -> PurchaseOrder:
        po = PurchaseOrder.objects.select_for_update().get(pk=po.pk)
        if po.status == PurchaseOrder.Status.APPROVED:
            return po
        if po.vendor.status in (VendorProfile.Status.BLACKLISTED, VendorProfile.Status.SUSPENDED):
            raise ValidationError(f"Cannot approve PO for {po.vendor.status} vendor {po.vendor.party.name}.")

        for line in po.lines.select_related("budget_line"):
            if line.budget_line:
                BudgetControlService.check_availability(
                    company=po.company, budget_line=line.budget_line,
                    amount=line.line_total, allow_override=allow_budget_override,
                )
                BudgetControlService.reserve_commitment(
                    company=po.company,
                    budget_line=line.budget_line,
                    project=po.project,
                    source_type="PURCHASE_ORDER",
                    source_id=po.id,
                    source_ref=po.po_number,
                    amount=line.line_total,
                )

        po.status = PurchaseOrder.Status.APPROVED
        po.approved_by = user
        po.save(update_fields=["status", "approved_by"])
        record_audit_event(
            company=po.company, actor=user, action="PO_APPROVED", entity_type="PurchaseOrder",
            entity_id=str(po.id), new_state={"po_number": po.po_number, "total": str(po.total_amount)},
        )
        return po

    @staticmethod
    @transaction.atomic
    def perform_three_way_match(
        *,
        company,
        user,
        po: PurchaseOrder,
        grn,
        supplier_invoice_no: str,
        invoice_date,
        billed_amount: Decimal,
        tax_amount: Decimal = Decimal("0.00"),
        tds_amount: Decimal = Decimal("0.00"),
        override_variance: bool = False,
        variance_reason: str = "",
    ) -> ThreeWayMatch:
        ordered_amt = po.subtotal_amount
        received_amt = grn.total_amount
        variance = (billed_amount - received_amt).quantize(Decimal("0.01"))
        tolerance = max(Decimal("100.00"), (received_amt * Decimal("0.02")).quantize(Decimal("0.01")))
        within_tol = abs(variance) <= tolerance

        if not within_tol and not override_variance:
            match = ThreeWayMatch.objects.create(
                company=company,
                purchase_order=po,
                grn=grn,
                supplier_invoice_no=supplier_invoice_no,
                invoice_date=invoice_date,
                ordered_amount=ordered_amt,
                received_amount=received_amt,
                billed_amount=billed_amount,
                tax_amount=tax_amount,
                tds_amount=tds_amount,
                variance_amount=variance,
                within_tolerance=False,
                variance_reason=variance_reason,
                status=ThreeWayMatch.Status.VARIANCE_HOLD,
                created_by=user,
            )
            raise ValidationError(
                f"3-Way Match variance ({variance}) exceeds tolerance ({tolerance}). Held ({match.id}) pending authorized variance approval."
            )

        policy = PostingRuleEngine.get_or_create_policy(company)
        party = po.vendor.party
        ap_acc = party.control_account or _find_acc(company, Account.ControlRole.SUNDRY_CREDITORS, "201")
        vat_acc = _find_acc(company, Account.ControlRole.INPUT_VAT, "125")
        tds_acc = _find_acc(company, Account.ControlRole.TDS_PAYABLE, "212")

        if policy.inventory_method == AccountingPolicy.InventoryMethod.PERPETUAL and policy.grni_on_receipt and grn.linked_voucher_id:
            dr_acc = _find_acc(company, Account.ControlRole.GRNI, "209")
            dr_label = f"Clear GRNI for {grn.grn_number} / {po.po_number}"
        elif policy.inventory_method == AccountingPolicy.InventoryMethod.PERPETUAL:
            dr_acc = _find_acc(company, Account.ControlRole.INVENTORY, "120")
            dr_label = f"Inventory Purchase ({po.po_number})"
        else:
            dr_acc = _find_acc(company, Account.ControlRole.DIRECT_EXPENSES, "501")
            dr_label = f"Periodic Material Purchase ({po.po_number})"

        if not dr_acc or not ap_acc:
            raise ValidationError("Required Purchase/GRNI or Sundry Creditors control account is missing.")

        lines_data = [
            {"account": dr_acc, "party": party if dr_acc.control_role == Account.ControlRole.GRNI else None, "debit": billed_amount, "credit": Decimal("0.00"), "project": po.project, "description": dr_label}
        ]
        if tax_amount > 0 and vat_acc:
            lines_data.append({"account": vat_acc, "debit": tax_amount, "credit": Decimal("0.00"), "project": po.project, "description": f"Input VAT on {supplier_invoice_no}"})
        net_payable = billed_amount + (tax_amount if vat_acc else Decimal("0.00"))
        if tds_amount > 0 and tds_acc:
            lines_data.append({"account": tds_acc, "debit": Decimal("0.00"), "credit": tds_amount, "project": po.project, "description": f"TDS Withheld on {supplier_invoice_no}"})
            net_payable -= tds_amount
        lines_data.append({"account": ap_acc, "party": party, "debit": Decimal("0.00"), "credit": net_payable, "project": po.project, "description": f"Supplier Invoice {supplier_invoice_no}"})

        voucher = VoucherService.create_draft(
            company=company,
            user=user,
            data={
                "voucher_type": Voucher.VoucherType.PURCHASE,
                "voucher_date": invoice_date,
                "project": po.project,
                "site": po.site,
                "party": party,
                "supplier_invoice_no": supplier_invoice_no,
                "reference_no": po.po_number,
                "narration": f"3-Way Matched Purchase Invoice {supplier_invoice_no} (PO: {po.po_number}, GRN: {grn.grn_number})",
                "gross_amount": billed_amount,
                "tax_amount": tax_amount,
                "tds_amount": tds_amount,
                "net_amount": net_payable,
            },
            lines_data=lines_data,
        )
        voucher.status = Voucher.Status.APPROVED
        voucher.approved_by = user
        voucher.save(update_fields=["status", "approved_by"])
        voucher = PostingService.post_voucher(voucher=voucher, user=user)

        for gl in grn.lines.select_related("po_line"):
            if gl.po_line:
                gl.po_line.billed_qty += gl.accepted_qty
                gl.po_line.save(update_fields=["billed_qty"])

        if all(pl.billed_qty >= pl.ordered_qty for pl in po.lines.all()):
            po.status = PurchaseOrder.Status.CLOSED
            po.save(update_fields=["status"])

        BudgetControlService.relieve_commitment(
            company=company, source_type="PURCHASE_ORDER", source_id=po.id, amount=billed_amount
        )

        match = ThreeWayMatch.objects.create(
            company=company,
            purchase_order=po,
            grn=grn,
            supplier_invoice_no=supplier_invoice_no,
            invoice_date=invoice_date,
            ordered_amount=ordered_amt,
            received_amount=received_amt,
            billed_amount=billed_amount,
            tax_amount=tax_amount,
            tds_amount=tds_amount,
            variance_amount=variance,
            within_tolerance=within_tol,
            variance_reason=variance_reason,
            voucher=voucher,
            status=ThreeWayMatch.Status.MATCHED_POSTED,
            created_by=user,
            approved_by=user,
        )
        return match

