import csv
import io
from datetime import date, datetime
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum
from django.utils import timezone

from apps.accounting.models import Account, AdvanceRecord, Party, PartyLedgerEntry
from apps.localization.bs_calendar import ad_to_bs
from apps.party_hub.models import (
    OpenItem,
    PartyDispute,
    PartyStatement,
    RABill,
    RetentionSchedule,
    StatementReconciliation,
    StatementReconciliationLine,
)
from .ar_billing_service import _q2, log_ar_audit


class ARStatementReconciliationService:
    """
    Formal Customer Account Statements & CSV/XLSX External Statement Matching Engine.
    Reconciliation differences are logged as explicit exceptions and NEVER auto-posted to GL.
    """

    @staticmethod
    @transaction.atomic
    def generate_customer_statement(*, company, user, party: Party, from_date: date, to_date: date, project=None, statement_type: str = PartyStatement.StatementType.CUSTOMER_STATEMENT) -> dict:
        if party.company_id != company.id or party.party_type != Party.PartyType.CUSTOMER:
            raise ValidationError("Selected party must be a customer of this company.")
        if from_date > to_date:
            raise ValidationError("Statement 'from_date' cannot be after 'to_date'.")

        ledger_qs = PartyLedgerEntry.objects.select_related("voucher", "project").filter(
            company=company,
            party=party,
            control_account__control_role=Account.ControlRole.SUNDRY_DEBTORS,
        )
        if project:
            ledger_qs = ledger_qs.filter(project=project)

        open_agg = ledger_qs.filter(entry_date__lt=from_date).aggregate(dr=Sum("debit"), cr=Sum("credit"))
        opening_bal = (open_agg["dr"] or Decimal("0.00")) - (open_agg["cr"] or Decimal("0.00"))

        period_entries = list(
            ledger_qs.filter(entry_date__gte=from_date, entry_date__lte=to_date).order_by("entry_date", "created_at")
        )
        running = opening_bal
        tx_rows = []
        for e in period_entries:
            running += (e.debit or Decimal("0.00")) - (e.credit or Decimal("0.00"))
            tx_rows.append({
                "date": e.entry_date.isoformat(),
                "bs_date": e.voucher.bs_date or ad_to_bs(e.entry_date).isoformat(),
                "voucher_id": str(e.voucher_id),
                "voucher_no": e.voucher.voucher_no,
                "voucher_type": e.voucher.voucher_type,
                "reference_no": e.reference_no or e.voucher.reference_no,
                "project_name": e.project.name if e.project else None,
                "narration": e.narration,
                "debit": str(e.debit),
                "credit": str(e.credit),
                "running_balance": str(running),
            })

        # Open item breakdown & separate disclosures
        oi_qs = OpenItem.objects.filter(
            company=company, party=party, hub_side=OpenItem.HubSide.RECEIVABLE, document_date__lte=to_date
        ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.WRITTEN_OFF, OpenItem.Status.REVERSED])
        if project:
            oi_qs = oi_qs.filter(project=project)

        overdue_bal = sum((o.remaining_amount for o in oi_qs if not o.is_unallocated_credit and o.due_date < to_date), Decimal("0.00"))
        unalloc_receipts = sum((o.remaining_amount for o in oi_qs if o.is_unallocated_credit), Decimal("0.00"))
        disputed_bal = sum((o.remaining_amount for o in oi_qs if not o.is_unallocated_credit and o.status == OpenItem.Status.DISPUTED), Decimal("0.00"))

        ret_bal = sum(
            (r.remaining_retention for r in RetentionSchedule.objects.filter(
                company=company, party=party, direction=RetentionSchedule.Direction.RECEIVABLE, hold_date__lte=to_date
            ).exclude(status=RetentionSchedule.Status.RELEASED)),
            Decimal("0.00"),
        )
        adv_bal = sum(
            (a.remaining_amount for a in AdvanceRecord.objects.filter(
                company=company, party=party, advance_type=AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE, issue_date__lte=to_date
            ).exclude(status__in=[AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED])),
            Decimal("0.00"),
        )
        uncertified_ra = sum(
            (b.current_gross_amount for b in RABill.objects.filter(
                company=company, party=party, voucher__isnull=True, bill_date__lte=to_date
            ).exclude(status__in=[RABill.WorkflowStatus.CANCELLED, RABill.WorkflowStatus.REJECTED, RABill.WorkflowStatus.SUPERSEDED])),
            Decimal("0.00"),
        )

        cnt = PartyStatement.objects.filter(company=company).count() + 1
        stmt_no = f"STMT-AR-{to_date.strftime('%Y%m')}-{cnt:04d}"
        stmt = PartyStatement.objects.create(
            company=company,
            party=party,
            statement_no=stmt_no,
            statement_type=statement_type,
            from_date=from_date,
            to_date=to_date,
            opening_balance=opening_bal,
            closing_balance=running,
            overdue_balance=overdue_bal,
            retention_balance=ret_bal,
            advance_balance=adv_bal,
            generated_by=user,
        )

        log_ar_audit(company, "PartyStatement", stmt.id, "CUSTOMER_STATEMENT_GENERATED", user, {"statement_no": stmt_no, "closing_balance": str(running)})
        return {
            "statement_id": str(stmt.id),
            "statement_no": stmt.statement_no,
            "party_id": str(party.id),
            "party_code": party.code,
            "party_name": party.name,
            "from_date": from_date.isoformat(),
            "to_date": to_date.isoformat(),
            "opening_balance": str(opening_bal),
            "closing_balance": str(running),
            "overdue_balance": str(overdue_bal),
            "unallocated_receipts": str(unalloc_receipts),
            "advance_balance": str(adv_bal),
            "retention_balance": str(ret_bal),
            "disputed_balance": str(disputed_bal),
            "uncertified_ra_billing": str(uncertified_ra),
            "transactions": tx_rows,
        }

    @staticmethod
    def parse_csv_rows(csv_text: str) -> list[dict]:
        reader = csv.DictReader(io.StringIO(csv_text.strip()))
        rows = []
        for idx, r in enumerate(reader, start=1):
            norm = {k.strip().lower().replace(" ", "_"): (v or "").strip() for k, v in r.items() if k}
            raw_date = norm.get("date") or norm.get("doc_date") or norm.get("transaction_date") or ""
            parsed_date = None
            for fmt in ("%Y-%m-%d", "%d/%m/%Y", "%m/%d/%Y"):
                try:
                    parsed_date = datetime.strptime(raw_date, fmt).date()
                    break
                except Exception:
                    continue
            rows.append({
                "line_no": idx,
                "date": parsed_date,
                "reference": norm.get("reference") or norm.get("ref") or norm.get("voucher_no") or norm.get("invoice_no") or "",
                "description": norm.get("description") or norm.get("narration") or norm.get("particulars") or "",
                "debit": _q2(norm.get("debit") or norm.get("dr") or "0.00"),
                "credit": _q2(norm.get("credit") or norm.get("cr") or "0.00"),
            })
        return rows

    @staticmethod
    @transaction.atomic
    def import_and_match(*, company, user, party: Party, statement_to: date, source_filename: str = "", csv_text: str = "", rows: list[dict] | None = None, customer_closing_balance: Decimal | None = None) -> StatementReconciliation:
        if party.company_id != company.id:
            raise ValidationError("Party does not belong to active company.")
        parsed = rows if rows is not None else ARStatementReconciliationService.parse_csv_rows(csv_text)
        if not parsed:
            raise ValidationError("No valid statement lines supplied for reconciliation.")

        # Company Trade Debtors closing balance as of statement_to
        agg = PartyLedgerEntry.objects.filter(
            company=company,
            party=party,
            entry_date__lte=statement_to,
            control_account__control_role=Account.ControlRole.SUNDRY_DEBTORS,
        ).aggregate(dr=Sum("debit"), cr=Sum("credit"))
        comp_closing = (agg["dr"] or Decimal("0.00")) - (agg["cr"] or Decimal("0.00"))

        if customer_closing_balance is None:
            cust_closing = sum((_q2(r.get("debit")) - _q2(r.get("credit")) for r in parsed), Decimal("0.00"))
        else:
            cust_closing = _q2(customer_closing_balance)

        cnt = StatementReconciliation.objects.filter(company=company).count() + 1
        recon = StatementReconciliation.objects.create(
            company=company,
            party=party,
            recon_no=f"RECON-{statement_to.strftime('%Y%m')}-{cnt:04d}",
            statement_to=statement_to,
            source_filename=source_filename or "uploaded_statement.csv",
            company_closing_balance=comp_closing,
            customer_closing_balance=cust_closing,
            variance_amount=comp_closing - cust_closing,
            created_by=user,
        )

        # Match against company OpenItems & PartyLedgerEntries (by reference number or voucher_no + amount)
        comp_items = list(OpenItem.objects.select_related("voucher").filter(company=company, party=party, hub_side=OpenItem.HubSide.RECEIVABLE, document_date__lte=statement_to))
        matched_oi_ids = set()
        has_exceptions = False

        for idx, r in enumerate(parsed, start=1):
            ref = (r.get("reference") or "").strip()
            ext_dr = _q2(r.get("debit"))
            ext_cr = _q2(r.get("credit"))
            ext_net = ext_dr - ext_cr
            ext_date = r.get("date")
            if isinstance(ext_date, str) and ext_date:
                ext_date = date.fromisoformat(ext_date)

            candidate = None
            for oi in comp_items:
                if oi.id in matched_oi_ids:
                    continue
                if ref and (oi.document_no.strip().lower() == ref.lower() or oi.voucher.voucher_no.strip().lower() == ref.lower()):
                    candidate = oi
                    break

            if not candidate and abs(ext_net) > 0:
                # Try exact amount fallback if date matches closely
                for oi in comp_items:
                    if oi.id in matched_oi_ids:
                        continue
                    oi_signed = oi.original_amount if not oi.is_unallocated_credit else -oi.original_amount
                    if oi_signed == ext_net and (not ext_date or abs((oi.document_date - ext_date).days) <= 7):
                        candidate = oi
                        break

            state = StatementReconciliationLine.MatchState.MISSING_IN_COMPANY
            variance = ext_net
            matched_v = None
            if candidate:
                matched_oi_ids.add(candidate.id)
                matched_v = candidate.voucher
                oi_signed = candidate.original_amount if not candidate.is_unallocated_credit else -candidate.original_amount
                variance = ext_net - oi_signed
                if variance == Decimal("0.00"):
                    if ext_date and abs((candidate.document_date - ext_date).days) > 7:
                        state = StatementReconciliationLine.MatchState.DATE_MISMATCH
                        has_exceptions = True
                    else:
                        state = StatementReconciliationLine.MatchState.MATCHED
                else:
                    state = StatementReconciliationLine.MatchState.AMOUNT_MISMATCH
                    has_exceptions = True
            else:
                has_exceptions = True
                if "deduct" in (r.get("description") or "").lower() or "tds" in (r.get("description") or "").lower():
                    state = StatementReconciliationLine.MatchState.UNRECOGNIZED_DEDUCTION

            StatementReconciliationLine.objects.create(
                reconciliation=recon,
                line_no=idx,
                ext_date=ext_date,
                ext_reference=ref[:80],
                ext_description=(r.get("description") or "")[:255],
                ext_debit=ext_dr,
                ext_credit=ext_cr,
                ext_net_amount=ext_net,
                matched_open_item=candidate,
                matched_voucher=matched_v,
                match_state=state,
                variance_amount=variance,
            )

        # Also surface items in Company books missing in customer statement
        line_cursor = len(parsed)
        for oi in comp_items:
            if oi.id not in matched_oi_ids:
                has_exceptions = True
                line_cursor += 1
                oi_signed = oi.original_amount if not oi.is_unallocated_credit else -oi.original_amount
                StatementReconciliationLine.objects.create(
                    reconciliation=recon,
                    line_no=line_cursor,
                    ext_date=oi.document_date,
                    ext_reference=oi.document_no[:80],
                    ext_description=f"Missing on customer statement: {oi.voucher.voucher_no}",
                    ext_debit=Decimal("0.00"),
                    ext_credit=Decimal("0.00"),
                    ext_net_amount=Decimal("0.00"),
                    matched_open_item=oi,
                    matched_voucher=oi.voucher,
                    match_state=StatementReconciliationLine.MatchState.MISSING_IN_CUSTOMER,
                    variance_amount=-oi_signed,
                )

        recon.status = (
            StatementReconciliation.Status.EXCEPTIONS_PENDING
            if (has_exceptions or recon.variance_amount != Decimal("0.00"))
            else StatementReconciliation.Status.MATCHED
        )
        recon.save(update_fields=["status"])
        log_ar_audit(company, "StatementReconciliation", recon.id, "STATEMENT_IMPORTED_MATCHED", user, {"recon_no": recon.recon_no, "variance": str(recon.variance_amount), "status": recon.status})
        return recon

