from decimal import Decimal
from sqlalchemy import func

from app.models import StateMaster


_STATE_ALIASES = {
    "new delhi": "delhi",
    "nct of delhi": "delhi",
    "national capital territory of delhi": "delhi",
    "orissa": "odisha",
    "pondicherry": "puducherry",
}


def _norm(value):
    text = " ".join(str(value or "").strip().lower().split())
    return _STATE_ALIASES.get(text, text)


def _gst_prefix(value):
    text = str(value or "").strip()
    if len(text) >= 2 and text[:2].isdigit():
        return text[:2].zfill(2)
    return ""


def _state_master_code_from_name(state_name):
    name = _norm(state_name)
    if not name:
        return ""

    # State master is small; resolving by normalized display name also handles
    # harmless whitespace/case differences and legacy spellings.
    rows = StateMaster.query.filter(StateMaster.is_active.is_(True)).all()
    for row in rows:
        if _norm(getattr(row, "name", None)) == name:
            code = str(getattr(row, "gst_state_code", None) or "").strip()
            if code:
                return code.zfill(2)
    return ""


def resolve_gst_state(obj=None, state_name=None, gstin=None):
    """Return a canonical GST state identity for a company/client branch."""
    if obj is not None:
        if not gstin:
            gstin = getattr(obj, "gst_no", None) or getattr(obj, "gst", None)
        if not state_name:
            state_name = getattr(obj, "state", None)

    code = _gst_prefix(gstin)
    if code:
        return {"code": code, "name": _norm(state_name), "source": "gstin"}

    state_master = getattr(obj, "state_master", None) if obj is not None else None
    if state_master is not None:
        master_code = str(getattr(state_master, "gst_state_code", None) or "").strip()
        master_name = getattr(state_master, "name", None)
        if master_code:
            return {"code": master_code.zfill(2), "name": _norm(master_name or state_name), "source": "state_master"}
        if master_name and not state_name:
            state_name = master_name

    code = _state_master_code_from_name(state_name)
    return {"code": code, "name": _norm(state_name), "source": "state_name" if state_name else "missing"}


def gst_supply_mode(company_branch, client_branch=None, billing_state=None, billing_gstin=None):
    seller = resolve_gst_state(company_branch)
    buyer = resolve_gst_state(client_branch, state_name=billing_state, gstin=billing_gstin)

    if seller["code"] and buyer["code"]:
        mode = "INTRA" if seller["code"] == buyer["code"] else "INTER"
    elif seller["name"] and buyer["name"]:
        mode = "INTRA" if seller["name"] == buyer["name"] else "INTER"
    else:
        mode = "UNKNOWN"

    return {
        "mode": mode,
        "seller_code": seller["code"],
        "buyer_code": buyer["code"],
        "seller_state": seller["name"],
        "buyer_state": buyer["name"],
    }


def tax_type_audit(document):
    """Audit whether stored CGST/SGST/IGST agrees with branch state geography."""
    company_branch = getattr(document, "company_branch", None)
    client_branch = getattr(document, "client_branch", None)
    quote = getattr(document, "quote", None)

    billing_state = None
    billing_gstin = None
    if quote is not None:
        billing_state = getattr(quote, "billing_state", None)
        billing_gstin = getattr(quote, "billing_gstin", None)

    supply = gst_supply_mode(
        company_branch,
        client_branch=client_branch,
        billing_state=billing_state,
        billing_gstin=billing_gstin,
    )

    cgst = Decimal(str(getattr(document, "cgst", None) or 0))
    sgst = Decimal(str(getattr(document, "sgst", None) or 0))
    igst = Decimal(str(getattr(document, "igst", None) or 0))
    tax_total = cgst + sgst + igst

    mismatch = False
    expected = ""
    if tax_total > Decimal("0.01"):
        if supply["mode"] == "INTRA" and igst > Decimal("0.01"):
            mismatch = True
            expected = "CGST + SGST"
        elif supply["mode"] == "INTER" and (cgst + sgst) > Decimal("0.01"):
            mismatch = True
            expected = "IGST"

    result = dict(supply)
    result.update({
        "mismatch": mismatch,
        "expected": expected,
        "stored": "IGST" if igst > Decimal("0.01") else ("CGST + SGST" if (cgst + sgst) > Decimal("0.01") else "No GST"),
    })
    return result
