# ============================================================
# ADDITIVE: every value a letter can use, read from the models (B2B: one company at a time) + the field list
# the "Generate New Letter" form shows.  Nothing is typed twice: HR only overrides what is different.
#
# Sources: Employee profile, Company master + Letterhead settings, Compensation package, latest Promotion /
# Transfer record, Exit clearance, Recruitment offer + job description, earlier Offer letter.
# ============================================================
import re
from decimal import Decimal, InvalidOperation

from django.utils import timezone

from . import letter_format as lf

MONTH_FMT = "%d %B %Y"
ONES = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
        "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
TENS = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]


# ------------------------------------------------------------------ small helpers
def fmt_date(d):
    return d.strftime(MONTH_FMT) if hasattr(d, "strftime") else (str(d) if d else "-")


def ordinal_date(d):
    return f"{d.day}{lf.ordinal_suffix(d.day)} {d.strftime('%B %Y')}" if hasattr(d, "strftime") else (str(d) if d else "-")


ISO_DATE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})(?:[T ].*)?$")
DMY_DATE = re.compile(r"^(\d{1,2})[/-](\d{1,2})[/-](\d{4})$")


def smart_date(value, key=""):
    """'2026-09-30' (date pickers), '30/09/2026' (date-like keys) or a date object -> '30 September 2026'. Other text stays."""
    from datetime import date as _date
    if hasattr(value, "strftime"):
        return fmt_date(value)
    t = str(value).strip()
    m = ISO_DATE.match(t)
    try:
        if m:
            return fmt_date(_date(int(m.group(1)), int(m.group(2)), int(m.group(3))))
        m = DMY_DATE.match(t)
        if m and (key.endswith("_date") or key in ("last_working_day", "effective_date")):
            return fmt_date(_date(int(m.group(3)), int(m.group(2)), int(m.group(1))))
    except ValueError:
        pass
    return t


def parse_money(v):
    """'3,60,000', '₹3,60,000.00 LPA', 360000, '4.5' -> Decimal rupees. Plain numbers below 1000 are read as LAKHS (LPA)."""
    if v in (None, "", "-"):
        return None
    if isinstance(v, (int, float, Decimal)):
        d = Decimal(str(v))
    else:
        s = re.sub(r"[^0-9.]", "", str(v))
        if not s or s == ".":
            return None
        try:
            d = Decimal(s)
        except InvalidOperation:
            return None
    return d * 100000 if d < 1000 else d


def inr(v, decimals=2):
    """Indian digit grouping: 360000 -> 3,60,000.00"""
    d = parse_money(v) if not isinstance(v, Decimal) else v
    if d is None:
        return "-"
    s = f"{abs(d):.{decimals}f}"
    whole, _, frac = s.partition(".")
    if len(whole) > 3:
        head, tail = whole[:-3], whole[-3:]
        whole = re.sub(r"(\d)(?=(\d\d)+$)", r"\1,", head) + "," + tail
    return ("-" if d < 0 else "") + whole + (("." + frac) if decimals else "")


def words_indian(n):
    n = int(n)
    if n == 0:
        return "Zero"

    def below_1000(x):
        out = ""
        if x >= 100:
            out += ONES[x // 100] + " Hundred "
            x %= 100
        if x >= 20:
            out += TENS[x // 10] + (" " + ONES[x % 10] if x % 10 else "")
        elif x:
            out += ONES[x]
        return out.strip()
    parts = []
    for div, name in ((10000000, "Crore"), (100000, "Lakh"), (1000, "Thousand")):
        if n >= div:
            parts.append(below_1000(n // div) + " " + name)
            n %= div
    if n:
        parts.append(below_1000(n))
    return " ".join(parts)


def _s(v):
    return "-" if v in (None, "") else str(v)


_BAD_START = re.compile(r"^(#{1,3} |>> |\.\. |- )")


def clean_value(v):
    """Values typed by users must never turn into layout markup."""
    s = str(v).replace("\r", " ").replace("\n", " ").replace("[[", "[ [")       # **bold** / ++underline++ stay allowed
    return ("\u200b" + s) if _BAD_START.match(s) else s


def format_body(template, variables):
    """Template + values -> final letter text (conditionals resolved, unknown {placeholders} become '-')."""
    from .letters import _Safe
    return lf.apply_conditionals(template, variables).format_map(_Safe(variables))


def responsibilities_markup(value):
    """Text / list / [{title, points[]}] -> '### Heading' + '- point' lines."""
    if not value:
        return ""
    lines = []
    if isinstance(value, str):
        for ln in value.replace("\r", "").split("\n"):
            ln = ln.strip(" \t-\u2022*")
            if not ln:
                continue
            lines.append(("### " + ln.rstrip(":")) if ln.endswith(":") else "- " + ln)
    elif isinstance(value, (list, tuple)):
        for item in value:
            if isinstance(item, dict):
                if item.get("title"):
                    lines.append("### " + str(item["title"]))
                lines += ["- " + str(p) for p in (item.get("points") or [])]
            elif str(item).strip():
                lines.append("- " + str(item).strip())
    return "\n".join(lines)


# ------------------------------------------------------------------ builder
def build_variables_v2(emp, extra=None, company=None, defaults=None):
    """-> (variables{str: str}, sources{key: 'where it came from'})."""
    from .letters import _legacy_build_variables
    from .models import EmployeeExtra, EmployeeLetter, PromotionRequest, TransferRequest
    company = company or emp.company
    ctx = lf.letterhead_context(company)
    v, src = {}, {}

    def put(key, value, source):
        if value not in (None, ""):
            v[key], src[key] = str(value), source

    base = _legacy_build_variables(emp, None)
    for k, val in base.items():
        v[k] = fmt_date(val) if hasattr(val, "strftime") else str(val)
        src[k] = "Employee profile"
    today = timezone.localdate()
    put("date", fmt_date(today), "Today")
    put("date_ordinal", ordinal_date(today), "Today")
    put("date_dmy", today.strftime("%d/%m/%Y"), "Today")
    put("date_plain", f"{today.day}\u2060 {today.strftime('%B %Y')}", "Today")   # stays 'plain' even inside [[ordinal_dates]] letters

    # ---- company master + letterhead
    put("company_legal_name", ctx["legal_name"], "Company / Letterhead")
    put("company_legal_name_title", ctx["legal_name"].title() if ctx["legal_name"].isupper() else ctx["legal_name"], "Company / Letterhead")
    put("company_short_name", ctx["short_name"], "Company / Letterhead")
    put("company_footer_name", ctx["footer_name"], "Company / Letterhead")
    put("cin", ctx["cin"], "Letterhead")
    put("website", ctx["website"], "Company / Letterhead")
    put("registered_office", ctx["registered_office"], "Company / Letterhead")
    put("place", ctx["place"], "Letterhead")
    put("signatory_name", ctx["signatory_name"], "Letterhead")
    put("signatory_title", ctx["signatory_title"], "Letterhead")
    put("rs", lf.currency_symbol(), "System")
    pol = ctx["policy"]
    for k, val in pol.items():
        put(k, val, "Letterhead policy defaults")
    for key in ("probation_months", "notice_probation_days", "notice_confirmed_days", "leave_in_probation_days"):
        try:
            put(key + "_words", words_indian(pol[key]).lower(), "Letterhead policy defaults")
        except Exception:                                       # noqa: BLE001
            pass

    # ---- employee / candidate
    name = (emp.name or "").strip()
    g = (getattr(emp, "Gender", "") or "").strip().lower()
    sal = "Mr" if g.startswith("m") else ("Ms" if g.startswith("f") else "")
    put("salutation", sal, "Employee profile")
    put("title_name", (sal + " " + name).strip(), "Employee profile")
    put("title_name_dot", ((sal + ". ") if sal else "") + name, "Employee profile")
    put("first_name", name.split()[0] if name else "", "Employee profile")
    he, his, him = ("he", "his", "him") if sal == "Mr" else ("she", "her", "her") if sal == "Ms" else ("they", "their", "them")
    for k, val in (("he_she", he), ("his_her", his), ("him_her", him), ("He_She", he.capitalize()), ("His_Her", his.capitalize())):
        put(k, val, "Employee profile (gender)")
    addr = (getattr(emp, "Current_Address", "") or getattr(emp, "Permanent_Address", "") or "").strip().replace("\n", ", ")
    put("employee_address", addr, "Employee profile")
    put("employee_email", emp.email, "Employee profile")
    put("work_location", getattr(emp, "Work_Location", ""), "Employee profile")
    put("employee_type", getattr(emp, "Employee_Type", ""), "Employee profile")
    put("joining_date_ordinal", ordinal_date(emp.Date_of_Joining), "Employee profile") if emp.Date_of_Joining else None
    extra_row = EmployeeExtra.objects.filter(employee=emp).select_related("reporting_manager").first()
    if extra_row and extra_row.reporting_manager_id:
        put("reporting_manager", extra_row.reporting_manager.name, "Reporting line")
        put("reporting_manager_designation", extra_row.reporting_manager.Designation, "Reporting line")

    # ---- compensation
    ctc = parse_money(base.get("ctc_annual")) if base.get("ctc_annual") not in (None, "-") else None
    if ctc is None and emp.Basic_Salary:
        ctc = Decimal(str(emp.Basic_Salary)) * 12
    if ctc is not None:
        put("ctc_annual_inr", inr(ctc), "Compensation package")
        put("ctc_lpa", f"{ctc / 100000:.2f}", "Compensation package")
    fixed = Decimal(str(emp.Basic_Salary)) if emp.Basic_Salary else (ctc / 12 if ctc else None)
    if fixed is not None:
        put("fixed_monthly_inr", inr(fixed), "Compensation package")
        put("fixed_monthly_words", words_indian(fixed), "Compensation package")

    # ---- earlier offer letter (for revision letters)
    offer_l = EmployeeLetter.objects.filter(company=company, employee=emp, letter_type="OFFER", is_active=True).order_by("-issued_on").first()
    put("offer_letter_date", fmt_date(offer_l.issued_on) if offer_l else (fmt_date(emp.Date_of_Joining) if emp.Date_of_Joining else ""),
        "Earlier offer letter" if offer_l else "Joining date")

    # ---- latest promotion / revision
    promo = (PromotionRequest.objects.filter(company=company, employee=emp, is_active=True,
                                             status__in=["Approved by Committee", "Executed"]).order_by("-id").first())
    if promo is not None:
        put("new_designation", promo.proposed_designation, "Latest promotion record")
        put("new_grade", promo.proposed_grade, "Latest promotion record")
        put("hike_percent", format(promo.hike_percent.normalize(), "f"), "Latest promotion record")
        put("effective_date", fmt_date(promo.effective_date) if promo.effective_date else "", "Latest promotion record")
    # ---- latest transfer
    tr = (TransferRequest.objects.filter(company=company, employee=emp, is_active=True).order_by("-id").first())
    if tr is not None:
        put("from_department", tr.from_department_name, "Latest transfer record")
        put("to_department", getattr(tr.to_department, "name", ""), "Latest transfer record")
        put("to_branch", getattr(tr.to_branch, "name", ""), "Latest transfer record")
        put("reporting_manager", getattr(tr.to_manager, "name", "") or v.get("reporting_manager"), "Latest transfer record")
        put("transfer_reason", tr.reason, "Latest transfer record")
        if tr.effective_date and "effective_date" not in src or (tr and tr.effective_date and src.get("effective_date") != "Latest promotion record"):
            put("effective_date", fmt_date(tr.effective_date), "Latest transfer record")

    # ---- exit
    try:
        from .models import ExitClearance
        ex = ExitClearance.objects.filter(company=company, employee=emp, is_active=True).order_by("-id").first()
    except Exception:                                           # noqa: BLE001
        ex = None
    if ex is not None:
        if ex.last_working_day:
            put("last_working_day", fmt_date(ex.last_working_day), "Exit clearance")
        if ex.resignation_date:
            put("resignation_date", fmt_date(ex.resignation_date), "Exit clearance")
    if emp.Date_of_Joining and (ex is not None and ex.last_working_day or hasattr(emp.Last_Working_Day, "year")):
        end = ex.last_working_day if ex is not None and ex.last_working_day else emp.Last_Working_Day
        if hasattr(end, "year"):
            months = (end.year - emp.Date_of_Joining.year) * 12 + end.month - emp.Date_of_Joining.month
            y, m = divmod(max(months, 0), 12)
            put("tenure_text", " ".join(x for x in (f"{y} year{'s' if y != 1 else ''}" if y else "", f"{m} month{'s' if m != 1 else ''}" if m else "") if x) or "less than a month", "Joining - last working day")

    # ---- candidate offer + job description
    offer = None
    try:
        offer = emp.offers.order_by("-id").first()
    except Exception:                                           # noqa: BLE001
        pass
    if offer is not None:
        put("designation", offer.designation, "Recruitment offer")
        if offer.target_joining_date:
            put("joining_date", fmt_date(offer.target_joining_date), "Recruitment offer")
            put("joining_date_ordinal", ordinal_date(offer.target_joining_date), "Recruitment offer")
        if offer.valid_until:
            put("offer_valid_until", fmt_date(offer.valid_until), "Recruitment offer")
        if offer.offered_ctc_lpa is not None:
            put("ctc_annual", f"{offer.offered_ctc_lpa * 100000:,.0f}", "Recruitment offer")
            put("ctc_annual_inr", inr(offer.offered_ctc_lpa * 100000), "Recruitment offer")
            put("ctc_lpa", f"{offer.offered_ctc_lpa:.2f}", "Recruitment offer")
            put("fixed_monthly_inr", inr(offer.offered_ctc_lpa * 100000 / 12), "Recruitment offer")
            put("fixed_monthly_words", words_indian(offer.offered_ctc_lpa * 100000 / 12), "Recruitment offer")
    try:
        jd = emp.recruitment_profile.requisition.job_description
        block = responsibilities_markup(jd.responsibilities)
        if block:
            v["responsibilities_block"], src["responsibilities_block"] = block, "Job description of the requisition"
    except Exception:                                           # noqa: BLE001
        pass

    # ---- values prepared by another module (e.g. the recruitment offer) - below what HR types
    for k, val in (defaults or {}).items():
        if val not in (None, "") and re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", str(k)) and not str(k).endswith("_block"):
            put(str(k), clean_value(smart_date(val, str(k))), "Recruitment offer")

    # ---- what HR typed always wins
    for k, val in (extra or {}).items():
        k = str(k)
        if k == "responsibilities":
            block = responsibilities_markup(val)
            if block:
                v["responsibilities_block"], src["responsibilities_block"] = block, "Entered manually"
            continue
        if k.endswith("_block") or not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", k):
            continue                                            # only the engine may inject markup blocks
        v[k], src[k] = clean_value(smart_date(val, k)), "Entered manually"
    # money typed by HR -> formatted twins
    for k in ("current_ctc", "revised_ctc", "ctc_annual"):
        if k in (extra or {}) or (k in v and k not in ("ctc_annual",)):
            m = parse_money(v.get(k))
            if m is not None:
                v[k + "_inr"] = inr(m)
    cur, rev, hike = parse_money(v.get("current_ctc")), parse_money(v.get("revised_ctc")), v.get("hike_percent")
    try:
        if cur is not None and rev is None and hike not in (None, "", "-"):
            rev = cur * (1 + Decimal(str(hike)) / 100)
            put("revised_ctc", f"{rev:,.0f}", "Computed from current CTC and hike %")
            put("revised_ctc_inr", inr(rev), "Computed from current CTC and hike %")
        if cur is not None and rev is not None and cur > 0 and hike in (None, "", "-", "0"):
            put("hike_percent", f"{(rev - cur) / cur * 100:.1f}".rstrip("0").rstrip("."), "Computed from current / revised CTC")
    except Exception:                                           # noqa: BLE001
        pass
    if "ctc_annual" in (extra or {}):
        put("ctc_annual_inr", inr(v["ctc_annual"]), "Entered manually")
    for k in ("effective_date", "joining_date", "last_working_day", "offer_letter_date"):
        if v.get(k) and v[k] != "-":
            put(k + "_dmy", v[k], "Same as " + k)
    real = lambda k: v.get(k) if v.get(k) not in (None, "", "-") else None
    if "designation_line" not in (extra or {}):
        put("designation_line", real("new_designation") or real("designation"), "Promotion record / Employee profile")
    if "revision_title" not in (extra or {}):
        put("revision_title", "Annual Revision", "Default")
    return v, src


# ------------------------------------------------------------------ the form definition per letter type
F = lambda key, label, type_="text", required=False, help_="": {"key": key, "label": label, "type": type_, "required": required, "help": help_}
COMMON = [F("employee_name", "Name", "readonly"), F("employee_code", "Employee / candidate code", "readonly"),
          F("designation", "Designation"), F("department", "Department")]
LETTER_FIELDS = {
    "OFFER": COMMON + [F("employee_address", "Address"), F("joining_date", "Date of joining", "date", True),
                       F("ctc_annual", "Annual CTC (Rs.)", "money", True, "Plain numbers below 1000 are read as lakhs"),
                       F("fixed_monthly_inr", "Fixed monthly component"), F("offer_valid_until", "Offer valid until", "date"),
                       F("responsibilities", "Roles & responsibilities", "textarea", False, "One point per line; a line ending with ':' is a heading")],
    "APPOINTMENT": COMMON + [F("joining_date", "Date of joining", "date", True), F("ctc_annual", "Annual CTC (Rs.)", "money"),
                             F("probation_period", "Probation period")],
    "CONFIRMATION": COMMON + [F("confirmation_date", "Confirmation date", "date", True)],
    "COMPENSATION_REVISION": COMMON + [F("revision_title", "Revision type (e.g. Mid Year appraisal)", "text", True),
                                       F("designation_line", "New designation (same if unchanged)"),
                                       F("effective_date", "Date of revision", "date", True), F("current_ctc", "Previous CTC (annual)", "money", True),
                                       F("revised_ctc", "Revised CTC (annual)", "money", False, "Leave empty to compute from hike %"),
                                       F("hike_percent", "Increment %", "number"), F("work_location", "Work location"),
                                       F("reporting_manager", "Reporting manager"), F("offer_letter_date", "Original offer letter date", "date"),
                                       F("revision_note", "Extra paragraph (optional)", "textarea")],
    "PROMOTION": COMMON + [F("new_designation", "New designation", "text", True), F("new_grade", "New grade / band"),
                           F("hike_percent", "Increment %", "number"), F("effective_date", "Effective date", "date", True)],
    "TRANSFER": COMMON + [F("from_department", "From department"), F("to_department", "To department", "text", True),
                          F("to_branch", "To branch / location"), F("reporting_manager", "Reporting manager"),
                          F("effective_date", "Effective date", "date", True), F("transfer_reason", "Reason", "textarea")],
    "DISCIPLINARY_WARNING": COMMON + [F("warning_level", "Warning level", "select", True), F("incident_date", "Incident date", "date"),
                                      F("warning_reason", "Matter / reason", "textarea", True)],
    "EXPERIENCE_CERTIFICATE": COMMON + [F("joining_date", "Date of joining", "date"), F("last_working_day", "Last working day", "date", True),
                                        F("experience_note", "Extra paragraph (optional)", "textarea")],
    "RELIEVING_EXPERIENCE": COMMON + [F("joining_date", "Date of joining", "date"), F("last_working_day", "Last working day", "date", True),
                                      F("relieving_note", "Extra paragraph (optional)", "textarea")],
}


def form_for(emp, letter_type, extra=None, company=None, defaults=None):
    """The 'Generate New Letter' form: every field with the value already read from the models and where it came from."""
    v, src = build_variables_v2(emp, extra, company, defaults)
    rows = []
    for f in LETTER_FIELDS.get(letter_type, COMMON):
        key = f["key"]
        val = v.get("responsibilities_block", "") if key == "responsibilities" else v.get(key, "")
        rows.append({**f, "value": "" if val in ("-", None) else val,
                     "source": src.get("responsibilities_block" if key == "responsibilities" else key, "Enter manually"),
                     "editable": f["type"] != "readonly"})
    return rows, v, src
