"""Response formatter — Indian number system, date normalization, code resolution.

Used to post-process LLM answers and SAP row data before display.
"""
from __future__ import annotations
import re
from datetime import datetime

_SAP_DATE_RE = re.compile(r"\b(20\d{2})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\b")


# ── Number formatting ─────────────────────────────────────────────────────────

def format_inr(value) -> str:
    """Format a raw rupee value into Indian system (Cr / L / plain)."""
    try:
        v = float(value)
    except (TypeError, ValueError):
        return str(value)
    sign = "-" if v < 0 else ""
    a = abs(v)
    if a >= 1_00_00_000:
        return f"{sign}₹{a / 1_00_00_000:,.2f} Cr"
    if a >= 1_00_000:
        return f"{sign}₹{a / 1_00_000:,.2f} L"
    return f"{sign}₹{a:,.0f}"


def indian_int(value) -> str:
    """Format an integer with Indian comma style (e.g. 12,34,567)."""
    try:
        v = int(value)
    except (TypeError, ValueError):
        return str(value)
    s = str(abs(v))
    sign = "-" if v < 0 else ""
    if len(s) <= 3:
        return sign + s
    result = s[-3:]
    s = s[:-3]
    while s:
        result = s[-2:] + "," + result
        s = s[:-2]
    return sign + result.lstrip(",")


# ── Date formatting ───────────────────────────────────────────────────────────

def format_date(date_str) -> str:
    """Convert SAP date string (YYYYMMDD or YYYY-MM-DD) to '15 Jan 2024'."""
    s = str(date_str or "").strip()
    if not s:
        return ""
    for fmt in ("%Y%m%d", "%Y-%m-%d", "%d/%m/%Y"):
        try:
            return datetime.strptime(s, fmt).strftime("%d %b %Y")
        except ValueError:
            pass
    return s


# ── Code resolution ───────────────────────────────────────────────────────────

def resolve_brand(code: str) -> str:
    """Map SAP purchasing-group code to brand name."""
    try:
        from data.master_data import get_brand_name
        name = get_brand_name(str(code))
        return name if name and name != code else code
    except Exception:
        return code


def resolve_branch(plant_code: str) -> str:
    """Map SAP plant code to branch name."""
    try:
        from data.master_data import get_branch_name
        name = get_branch_name(str(plant_code))
        return name if name and name != plant_code else plant_code
    except Exception:
        return plant_code


# ── Answer post-processing ────────────────────────────────────────────────────

def normalize_answer(text: str) -> str:
    """Post-process an LLM answer: convert embedded SAP YYYYMMDD dates to readable."""
    if not text:
        return text

    def _date_sub(m):
        try:
            return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).strftime("%d %b %Y")
        except Exception:
            return m.group(0)

    return _SAP_DATE_RE.sub(_date_sub, text)


# ── Row-level formatting ──────────────────────────────────────────────────────

def format_rows(rows: list[dict]) -> list[dict]:
    """Format SAP result rows in-place: dates → readable, codes → names."""
    out = []
    for row in rows:
        new_row = {}
        for k, v in row.items():
            ku = k.upper()
            if "DATE" in ku and isinstance(v, str) and len(v) == 8 and v.isdigit():
                new_row[k] = format_date(v)
            elif ku in ("BRANDCODE", "BRAND"):
                new_row[k] = resolve_brand(str(v)) if v else v
            elif ku == "PLANT":
                new_row[k] = resolve_branch(str(v)) if v else v
            else:
                new_row[k] = v
        out.append(new_row)
    return out
