"""lfcs-bid-vs-qs-compare@v1 (lightweight) — generates pricing-history per-line MD files.

Per Stage 5 milestone 1 § 5. Triggered on Bid.Status = Submitted.

Lightweight v1 scope:
  - For each Bid Line Item on the Submitted bid, write a pricing-history MD file
    matching the existing per-line schema in
    `Operations/lfcs-standards/pricing-history/{job}-{boq_section}-{slug}.md`
  - Populate `qs_unit_rate_aud` if any Bid Line Item Override on this line has
    `reviewer_type` starting `Commercial-External-` (Robert / Civil Experts / Other)
  - Set `qs_share_status` accordingly (`shared-verbal` for typed-fallback path
    until voice ships)

Full QS-comparison features (cross-bid lookup, anonymised hashing per Stage 4
"Open Decision (b)-7", etc.) deferred to milestone 2 v2.
"""

from __future__ import annotations

import datetime as dt
import re
from pathlib import Path

from . import airtable_client as at
from .config import BASE_ID, FIELD, TBL


PRICING_HISTORY_DIR = Path(
    r"C:\Users\mclou\rateright-growth-deploy\HQ-Vault\11_OpsMan_LFCS"
    r"\Operations\lfcs-standards\pricing-history"
)


def _slugify(s: str) -> str:
    return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")[:40]


def _safe_get(rec: dict, table_key: str, field_name: str, default=None):
    return rec.get("fields", {}).get(FIELD[table_key][field_name], default)


def _job_slug(job_record: dict) -> tuple[str, str, str]:
    """Return (job_no, client, location) from a Job record."""
    f = FIELD["Jobs"]
    return (
        str(job_record["fields"].get(f["Job_Number"], "unknown")),
        str(job_record["fields"].get(f["Client"], "unknown")),
        str(job_record["fields"].get(f["job_category"], "")),
    )


def export_pricing_history_for_bid(
    bid_record_id: str, output_dir: Path | None = None
) -> list[Path]:
    """Generate per-line pricing-history MD files for a Submitted bid. Returns paths written."""
    output_dir = output_dir or PRICING_HISTORY_DIR
    output_dir.mkdir(parents=True, exist_ok=True)

    bid = at.get_record(BASE_ID, TBL["Bids"], bid_record_id)
    job_links = bid["fields"].get(FIELD["Bids"]["Job"], [])
    if not job_links:
        return []
    job = at.get_record(BASE_ID, TBL["Jobs"], job_links[0])
    job_no, client, category = _job_slug(job)

    # Fetch line items linked to this bid
    f_bli = FIELD["Bid_Line_Items"]
    line_items: list[dict] = []
    for bli in at.list_records(BASE_ID, TBL["Bid_Line_Items"]):
        if bid_record_id in (bli["fields"].get(f_bli["Bid"], []) or []):
            line_items.append(bli)

    # Fetch external QS overrides indexed by bid_line_item id
    f_ovr = FIELD["Bid_Line_Item_Overrides"]
    external_overrides: dict[str, list[dict]] = {}
    for ovr in at.list_records(BASE_ID, TBL["Bid_Line_Item_Overrides"]):
        rt = ovr["fields"].get(f_ovr["reviewer_type"], "")
        if not rt.startswith("Commercial-External-"):
            continue
        for bli_id in ovr["fields"].get(f_ovr["bid_line_item"], []) or []:
            external_overrides.setdefault(bli_id, []).append(ovr)

    written: list[Path] = []
    for bli in line_items:
        path = _write_pricing_history_md(
            bli, job_no, client, category, external_overrides.get(bli["id"], []), output_dir
        )
        if path:
            written.append(path)
    return written


def _write_pricing_history_md(
    bli: dict,
    job_no: str,
    client: str,
    category: str,
    qs_overrides: list[dict],
    output_dir: Path,
) -> Path | None:
    f = FIELD["Bid_Line_Items"]
    description = bli["fields"].get(f["Description"], "")
    item_no = bli["fields"].get(f["Item_no"], "")
    rate = bli["fields"].get(f["Rate_ex_GST"])
    qty = bli["fields"].get(f["Qty"])
    unit = bli["fields"].get(f["Unit"], "")
    if rate is None or not description:
        return None

    qs_unit_rate = None
    qs_share_status = "not-asked"
    if qs_overrides:
        # Latest external override wins
        f_ovr = FIELD["Bid_Line_Item_Overrides"]
        latest = max(
            qs_overrides, key=lambda o: o["fields"].get(f_ovr["created_at"], "")
        )
        qs_unit_rate = latest["fields"].get(f_ovr["override_rate_ex_gst"])
        qs_share_status = "shared-verbal"

    delta_pct = None
    if qs_unit_rate is not None and rate:
        delta_pct = (qs_unit_rate - rate) / rate * 100

    slug = _slugify(description)
    boq_section = str(item_no) if item_no else "L-unknown"
    path = output_dir / f"{job_no}-{boq_section}-{slug}.md"

    body = f"""---
job_no: {job_no}
client: {client}
job_category: {category}
boq_section: {boq_section}
description: |
  {description}
unit: {unit}
quantity: {qty}
unit_rate_aud: {rate}
qs_unit_rate_aud: {qs_unit_rate if qs_unit_rate is not None else "null"}
qs_share_status: {qs_share_status}
delta_pct: {f"{delta_pct:.2f}" if delta_pct is not None else "null"}
date_priced: {dt.date.today().isoformat()}
outcome: submitted
source_bid_line_item: {bli["id"]}
---

[per-line pricing-history entry generated by lfcs-bid-vs-qs-compare@v1]
"""
    path.write_text(body, encoding="utf-8")
    return path
