"""
Direct-OpenAI diagnostic sweep for apply-leave date extraction.

Calls the REAL LLM slot-extraction prompt (services.ai_service.
_build_leave_slot_extraction_prompt + _call_llm) for a curated set of
date-phrase leave queries -- the exact same call leave_action_node makes on
turn 1 of an apply-leave conversation -- and compares three things side by
side for each query:

  1. The LLM's raw, uncorrected from_date/to_date guess.
  2. Whether services.date_resolver recognizes ANY deterministic pattern in
     the query text at all, and what it resolves to if so.
  3. The FINAL result production actually ships today, after
     leave_action_service._apply_deterministic_date_overrides has had a
     chance to silently correct the LLM's guess.

This is read-only against the app (no leave_slot_service, no erp_client, no
leave_action_node call -- just the extraction + resolver + override layers
in isolation) and makes real, live OpenAI calls, so it needs OPENAI_API_KEY
in .env and does cost a small amount of real API usage.

Purpose: size and characterize the ONE path this system currently has no
safety net for -- queries where date_resolver finds nothing and the LLM's
raw guess is the only source of the date -- before implementing a
confirmation step for exactly that gap (see the "Would trigger new
confirmation step?" column). Every other row (deterministic layer found a
match) is expected to keep being silently auto-corrected, matching
tests/test_leave_action.py::TestDeterministicDateOverride's existing,
deliberately-tested behavior.

Run:    python tests/date_extraction_direct_openai_sweep.py
Writes: <repo>/reports/date_extraction_direct_openai_sweep_<timestamp>.xlsx
"""

import asyncio
import datetime
import os
import sys
import time
from pathlib import Path

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()

from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.utils import get_column_letter

import services.ai_service as ai_service
import services.date_resolver as date_resolver
import services.hr_graph as hr_graph
import services.leave_action_service as leave_action_service

REPO_ROOT = Path(__file__).resolve().parent.parent

# ── Styling (matches tests/generate_hr_leave_xlsx_report.py) ────────────────
HEADER_FILL = PatternFill(start_color="1F4E78", end_color="1F4E78", fill_type="solid")
HEADER_FONT = Font(color="FFFFFF", bold=True)
SECTION_FILL = PatternFill(start_color="2E75B6", end_color="2E75B6", fill_type="solid")
SECTION_FONT = Font(color="FFFFFF", bold=True)
PASS_FILL = PatternFill(start_color="C6EFCE", end_color="C6EFCE", fill_type="solid")
PASS_FONT = Font(color="006100")
FAIL_FILL = PatternFill(start_color="FFC7CE", end_color="FFC7CE", fill_type="solid")
FAIL_FONT = Font(color="9C0006", bold=True)
WARN_FILL = PatternFill(start_color="FFEB9C", end_color="FFEB9C", fill_type="solid")
WARN_FONT = Font(color="9C6500", bold=True)
THIN_BORDER = Border(*([Side(style="thin", color="D9D9D9")] * 4))

_KNOWN_SLUGS = ["casual_leave", "sick_leave", "earned_leave", "comp_off", "leave_without_pay", "short_leave"]

# ── Curated query set ────────────────────────────────────────────────────────
# (label, query) -- label groups related queries for the report; query is the
# exact text sent through the extraction prompt.
QUERIES = [
    ("Original bug report", "apply leave for next week wednesday for sick leave reason is health issue"),
    ("Isolated phrase", "next week wednesday"),
    ("Control -- bare weekday", "next wednesday"),
    ("Control -- already-passing case", "next monday"),
    ("Compound, different weekday", "next week friday"),
    ("Compound, different weekday 2", "next week thursday"),
    ("Two-weeks-out phrasing", "next to next monday"),
    ("Two-weeks-out, worded differently", "week after next"),
    ("Month-relative", "first monday of next month"),
    ("Month-relative, different weekday", "first wednesday of next month"),
    ("Ambiguous month-relative", "last week of this month"),
    ("Colloquial 'week after'", "the monday after next"),
    ("Historical live bug (duration+date)", "I want to apply 20 days leaves from 12th november"),
    ("Historical live bug (compound weekday)", "next to next monday leave"),
    ("Duration + weekday combo", "apply leave from next week wednesday for 3 days"),
    ("Half-day + weekday", "half day leave next wednesday afternoon"),
    ("Tomorrow (control)", "apply leave for tomorrow"),
    ("Day after tomorrow (control)", "apply leave for the day after tomorrow"),
    ("Yesterday (control, past-date guard)", "apply leave for yesterday"),
    ("Today (control)", "apply leave for today"),
    ("Named-month range", "leave from october first wednesday to october next saturday"),
    ("Week-of-month range", "apply leave for the first week of november"),
    ("Week-of-month narrowed to weekday", "november first week coming wednesday for 1 day"),
    ("Bare weekday-to-weekday range", "leave from upcoming wednesday to next sunday"),
    ("Invalid range (end before start)", "apply leave from 20th september to 10th september"),
    ("Invalid calendar date", "apply leave on 30th february"),
    ("No fixed calendar answer -- long weekend", "apply leave for next long weekend"),
    ("No fixed calendar answer -- named holiday", "leave for next eid"),
    ("No fixed calendar answer -- historical holiday", "same dates as last year's diwali break"),
    ("Relative to another stated date, not today", "leave starting the day after my project deadline on the 15th"),
    ("Quarter-relative (unsupported)", "apply leave for the first working day of next quarter"),
    ("Bare 'next week' (no weekday)", "apply leave for next week"),
    ("Explicit ISO date (control -- always LLM-only)", "apply leave on 2026-09-15"),
    ("Ordinal date, no month context", "apply leave on the 5th"),
    ("Casual phrasing, no explicit date word", "book me off this friday"),
    ("Casual phrasing 2", "I need wednesday off next week"),
    ("Sick leave + vague date", "sick leave, not feeling well, need tomorrow off"),
    ("Multi-day span, weekday anchored", "leave from next monday to next friday"),
    ("Multi-day, month name only", "leave for the whole of november"),
    ("Relative + explicit year", "apply leave for next wednesday 2027"),
    ("Weekend leave (no such concept)", "I want leave this weekend"),
]


def _weekday_name(d: datetime.date) -> str:
    return d.strftime("%A")


def _find_named_weekday(query: str) -> str | None:
    text = query.lower()
    for name in date_resolver._WEEKDAYS:
        if name in text:
            return name
    return None


def _deterministic_candidate(query: str, today: datetime.date):
    """Runs every date_resolver pattern function against `query`, in the same
    precedence order leave_action_service._apply_deterministic_date_overrides
    uses, and
    returns (matched: bool, phrase: str|None, from_date: str|None, to_date: str|None, kind: str|None)."""
    range_result = date_resolver.resolve_date_range_phrase(query, today)
    if range_result and range_result[1] is not None:
        first, second = range_result
        return True, first["matched_phrase"], first["from_date"], second["from_date"], "named_month_range"

    week_result = date_resolver.resolve_week_of_month_phrase(query, today)
    if week_result:
        first, second = week_result
        narrowed = date_resolver.weekday_within_span(
            query, datetime.date.fromisoformat(first["from_date"]), datetime.date.fromisoformat(second["from_date"]),
        )
        if narrowed is None:
            return True, first["matched_phrase"], first["from_date"], second["from_date"], "week_of_month"
        return True, narrowed["matched_phrase"], narrowed["from_date"], narrowed["from_date"], "week_of_month_narrowed"

    weekday_range_result = date_resolver.resolve_relative_date_range_phrase(query, today)
    if weekday_range_result and weekday_range_result[1] is not None:
        first, second = weekday_range_result
        return True, first["matched_phrase"], first["from_date"], second["from_date"], "bare_weekday_range"

    resolved = date_resolver.resolve_relative_date_phrase(query, today)
    if resolved:
        return True, resolved["matched_phrase"], resolved["from_date"], resolved["from_date"], resolved["matched_kind"]

    if weekday_range_result:  # single-endpoint bare range
        first, _ = weekday_range_result
        return True, first["matched_phrase"], first["from_date"], None, "bare_weekday_range_single"

    return False, None, None, None, None


async def run_one(label: str, query: str, today_app_tz: datetime.date, semaphore: asyncio.Semaphore) -> dict:
    async with semaphore:
        row = {
            "label": label, "query": query, "today_app_tz": today_app_tz.isoformat(),
            "today_naive": datetime.date.today().isoformat(),
            "llm_from_date": None, "llm_to_date": None, "llm_weekday_valid": "n/a",
            "det_matched": False, "det_phrase": None, "det_from_date": None, "det_to_date": None, "det_kind": None,
            "final_from_date": None, "final_to_date": None,
            "would_trigger_confirmation": False, "error": None,
        }
        try:
            prompt = ai_service._build_leave_slot_extraction_prompt(query, {}, known_leave_type_slugs=_KNOWN_SLUGS)
            raw = await ai_service._call_llm(prompt, max_tokens=200, model=ai_service.INTENT_MODEL)
            text = ai_service._extract_text(raw)
            extracted = ai_service._safe_json_parse(text)
        except Exception as e:
            row["error"] = f"LLM call/parse failed: {e}"
            extracted = {}

        llm_from = extracted.get("from_date")
        llm_to = extracted.get("to_date")
        row["llm_from_date"] = llm_from
        row["llm_to_date"] = llm_to

        named_weekday = _find_named_weekday(query)
        if llm_from and named_weekday:
            try:
                actual_wd = _weekday_name(datetime.date.fromisoformat(llm_from)).lower()
                row["llm_weekday_valid"] = "YES" if actual_wd == named_weekday else f"NO (got {actual_wd})"
            except ValueError:
                row["llm_weekday_valid"] = "NO (invalid date)"
        elif llm_from:
            row["llm_weekday_valid"] = "n/a (no weekday named)"

        det_matched, det_phrase, det_from, det_to, det_kind = _deterministic_candidate(query, today_app_tz)
        row["det_matched"] = det_matched
        row["det_phrase"] = det_phrase
        row["det_from_date"] = det_from
        row["det_to_date"] = det_to
        row["det_kind"] = det_kind

        slots = {"step": "collecting", "leave_type": None, "from_date": None,
                  "to_date": None, "session_type_slug": None, "reason": None}
        for field in ("leave_type", "from_date", "to_date", "session_type_slug", "reason"):
            if extracted.get(field):
                slots[field] = extracted[field]
        try:
            leave_action_service._apply_deterministic_date_overrides(query, slots, extracted, today_app_tz)
        except Exception as e:
            row["error"] = f"{row['error'] or ''} | override failed: {e}".strip(" |")
        row["final_from_date"] = slots.get("from_date")
        row["final_to_date"] = slots.get("to_date")

        # Trigger condition #2 from the plan: deterministic layer found
        # NOTHING at all, while the LLM's raw extraction supplied a date --
        # the one path with zero cross-check today.
        row["would_trigger_confirmation"] = bool(llm_from) and not det_matched

        return row


async def main():
    today_app_tz = leave_action_service._today_in_app_timezone()
    print(f"Anchor 'today' (app timezone): {today_app_tz} ({_weekday_name(today_app_tz)})")
    print(f"Anchor 'today' (naive server-local, what the extraction prompt actually uses today): "
          f"{datetime.date.today()} ({_weekday_name(datetime.date.today())})")
    if today_app_tz != datetime.date.today():
        print("  ^ NOTE: these disagree right now -- exactly the timezone bug flagged in the plan.")

    semaphore = asyncio.Semaphore(6)
    print(f"\nRunning {len(QUERIES)} queries through the real OpenAI extraction call (provider={ai_service.ACTIVE_LLM_PROVIDER}, "
          f"model={ai_service.INTENT_MODEL}, concurrency=6)...")
    start = time.monotonic()

    tasks = [run_one(label, query, today_app_tz, semaphore) for label, query in QUERIES]
    results = []
    for i, coro in enumerate(asyncio.as_completed(tasks), start=1):
        results.append(await coro)
        if i % 10 == 0 or i == len(tasks):
            print(f"  ...{i}/{len(tasks)} done")

    elapsed = time.monotonic() - start
    # Restore original ordering (as_completed scrambles it).
    order = {(label, query): idx for idx, (label, query) in enumerate(QUERIES)}
    results.sort(key=lambda r: order[(r["label"], r["query"])])

    print(f"\nCompleted in {elapsed:.1f}s")
    return results, today_app_tz, elapsed


def build_report(results: list, today_app_tz: datetime.date, elapsed: float, out_path: Path) -> None:
    wb = Workbook()

    total = len(results)
    llm_invalid = sum(1 for r in results if r["llm_weekday_valid"].startswith("NO"))
    det_matched_count = sum(1 for r in results if r["det_matched"])
    would_trigger = sum(1 for r in results if r["would_trigger_confirmation"])
    errors = sum(1 for r in results if r["error"])

    # ── Sheet 1: Summary ──────────────────────────────────────────────────
    summary = wb.active
    summary.title = "Summary"
    summary.sheet_view.showGridLines = False

    summary.merge_cells("A1:D1")
    title_cell = summary["A1"]
    title_cell.value = "Direct-OpenAI Date Extraction Sweep -- apply-leave date phrasing"
    title_cell.font = Font(bold=True, size=14, color="FFFFFF")
    title_cell.fill = HEADER_FILL
    title_cell.alignment = Alignment(horizontal="center", vertical="center")
    summary.row_dimensions[1].height = 28

    meta = [
        ("Generated", datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
        ("Anchor 'today' (app timezone)", f"{today_app_tz} ({_weekday_name(today_app_tz)})"),
        ("LLM provider / model", f"{ai_service.ACTIVE_LLM_PROVIDER} / {ai_service.INTENT_MODEL}"),
        ("Total queries", total),
        ("Runtime", f"{elapsed:.1f}s"),
        ("LLM guess weekday-inconsistent (hallucinated)", llm_invalid),
        ("Deterministic layer matched something", det_matched_count),
        ("Would trigger NEW confirmation step (no safety net today)", would_trigger),
        ("Errors", errors),
        ("Note", "Real live OpenAI calls; mocked nothing -- this reflects actual production extraction behavior."),
    ]
    for i, (k, v) in enumerate(meta, start=2):
        ka = summary.cell(row=i, column=1, value=k)
        ka.font = Font(bold=True, color="FFFFFF")
        ka.fill = SECTION_FILL
        ka.border = THIN_BORDER
        va = summary.cell(row=i, column=2, value=v)
        va.border = THIN_BORDER
        if k.startswith("Would trigger") and would_trigger:
            va.fill, va.font = WARN_FILL, WARN_FONT
        elif k.startswith("LLM guess weekday-inconsistent") and llm_invalid:
            va.fill, va.font = FAIL_FILL, FAIL_FONT
        elif k == "Errors" and errors:
            va.fill, va.font = FAIL_FILL, FAIL_FONT
    summary.column_dimensions["A"].width = 46
    summary.column_dimensions["B"].width = 60

    # ── Sheet 2: All Results ─────────────────────────────────────────────
    detail = wb.create_sheet("All Results")
    detail.sheet_view.showGridLines = False
    headers = [
        "#", "Label", "Query", "Today (app tz)", "LLM from_date", "LLM to_date",
        "LLM weekday valid?", "Det. matched?", "Det. phrase", "Det. from_date", "Det. to_date",
        "Det. kind", "Final from_date", "Final to_date", "Would trigger confirmation?", "Error",
    ]
    for c, h in enumerate(headers, start=1):
        detail.cell(row=1, column=c, value=h)
    detail.freeze_panes = "A2"
    for col in range(1, len(headers) + 1):
        cell = detail.cell(row=1, column=col)
        cell.fill = HEADER_FILL
        cell.font = HEADER_FONT
        cell.alignment = Alignment(vertical="center", wrap_text=True)
        cell.border = THIN_BORDER

    for i, r in enumerate(results, start=1):
        values = [
            i, r["label"], r["query"], r["today_app_tz"], r["llm_from_date"], r["llm_to_date"],
            r["llm_weekday_valid"], "YES" if r["det_matched"] else "no", r["det_phrase"],
            r["det_from_date"], r["det_to_date"], r["det_kind"], r["final_from_date"], r["final_to_date"],
            "YES" if r["would_trigger_confirmation"] else "no", r["error"] or "",
        ]
        row_idx = i + 1
        for c, v in enumerate(values, start=1):
            cell = detail.cell(row=row_idx, column=c, value=v)
            cell.border = THIN_BORDER
            if c in (3, 9, 16):
                cell.alignment = Alignment(wrap_text=True)
        wd_cell = detail.cell(row=row_idx, column=7)
        if isinstance(wd_cell.value, str) and wd_cell.value.startswith("NO"):
            wd_cell.fill, wd_cell.font = FAIL_FILL, FAIL_FONT
        trig_cell = detail.cell(row=row_idx, column=15)
        if r["would_trigger_confirmation"]:
            trig_cell.fill, trig_cell.font = WARN_FILL, WARN_FONT
        else:
            trig_cell.fill, trig_cell.font = PASS_FILL, PASS_FONT
        if r["error"]:
            detail.cell(row=row_idx, column=16).fill = FAIL_FILL

    detail.auto_filter.ref = f"A1:{get_column_letter(len(headers))}{len(results) + 1}"
    widths = [4, 24, 42, 14, 13, 13, 20, 12, 26, 13, 13, 22, 13, 13, 22, 30]
    for i, w in enumerate(widths, start=1):
        detail.column_dimensions[get_column_letter(i)].width = w

    out_path.parent.mkdir(parents=True, exist_ok=True)
    wb.save(out_path)


if __name__ == "__main__":
    results, today_app_tz, elapsed = asyncio.run(main())

    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    out_path = REPO_ROOT / "reports" / f"date_extraction_direct_openai_sweep_{timestamp}.xlsx"
    build_report(results, today_app_tz, elapsed, out_path)

    total = len(results)
    llm_invalid = sum(1 for r in results if r["llm_weekday_valid"].startswith("NO"))
    det_matched_count = sum(1 for r in results if r["det_matched"])
    would_trigger = sum(1 for r in results if r["would_trigger_confirmation"])
    print(f"\n{'=' * 70}")
    print(f"Date extraction sweep -- {total} queries")
    print(f"{'=' * 70}")
    print(f"  LLM guess weekday-inconsistent (hallucinated): {llm_invalid}/{total}")
    print(f"  Deterministic layer matched something:         {det_matched_count}/{total}")
    print(f"  Would trigger NEW confirmation step:            {would_trigger}/{total}")
    print(f"{'=' * 70}")
    print(f"\nExcel report written to: {out_path}")
