from __future__ import annotations

import argparse
import json
import re
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_JSON = ROOT / "GatherTradingData.json"
DEFAULT_REPORT = ROOT / "Temp" / "operational_report.md"


def load_json(path: Path) -> dict[str, Any]:
    payload = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(payload, dict):
        raise ValueError("payload must be object")
    return payload


def extract_watch_section(text: str) -> str:
    marker = "투명한 감시 원장"
    idx = text.find(marker)
    if idx < 0:
        return ""
    tail = text[idx:]
    m = re.search(r"\n##\s+", tail[1:])
    return tail if not m else tail[: m.start() + 1]


def parse_markdown_rows(section: str) -> list[list[str]]:
    rows: list[list[str]] = []
    for line in section.splitlines():
        if not line.strip().startswith("|"):
            continue
        cols = [c.strip() for c in line.strip().strip("|").split("|")]
        rows.append(cols)
    # header, separator 제외
    if len(rows) <= 2:
        return []
    return rows[2:]


def text(v: Any) -> str:
    return str(v or "").strip()


def parse_list(value: Any) -> list[dict[str, Any]]:
    if isinstance(value, list):
        return [r for r in value if isinstance(r, dict)]
    if isinstance(value, str):
        s = value.strip()
        if s.startswith("["):
            try:
                parsed = json.loads(s)
                if isinstance(parsed, list):
                    return [r for r in parsed if isinstance(r, dict)]
            except Exception:
                return []
    return []

def localize_state(state: str) -> str:
    m = {
        "PENDING": "대기",
        "TP1_ALREADY_TRIGGERED": "1차 익절 이미 발동",
        "TP2_ALREADY_TRIGGERED": "2차 익절 이미 발동",
        "INVALID_TP_STALE": "오래된 익절값",
        "TRAILING_STOP_PRIORITY_SECULAR_LEADER": "추적손절 우선(주도주)",
        "DEFERRED_SECULAR_LEADER": "주도주 익절 지연",
        "DEFERRED_SECULAR_LEADER_OVERHEAT_PENDING": "주도주 과열 보류",
        "ALREADY_TRIGGERED": "이미 발동",
    }
    return m.get(state, state)


def main() -> int:
    parser = argparse.ArgumentParser(description="Validate WATCH ledger rows against harness json source.")
    parser.add_argument("--json", default=str(DEFAULT_JSON))
    parser.add_argument("--report", default=str(DEFAULT_REPORT))
    args = parser.parse_args()

    json_path = Path(args.json)
    report_path = Path(args.report)
    if not json_path.is_absolute():
        json_path = ROOT / json_path
    if not report_path.is_absolute():
        report_path = ROOT / report_path

    payload = load_json(json_path)
    report = report_path.read_text(encoding="utf-8")
    section = extract_watch_section(report)
    if not section:
        print("WATCH_LEDGER_FAIL: section missing")
        return 1

    data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
    h = data.get("_harness_context") if isinstance(data.get("_harness_context"), dict) else {}
    ob = parse_list(h.get("order_blueprint_json"))
    prices_rows = parse_list(h.get("prices_json"))
    prices = {text(r.get("ticker")): r for r in prices_rows}

    watch_rows_json = [r for r in ob if text(r.get("validation_status")) != "PASS"]
    watch_rows_md = parse_markdown_rows(section)
    # placeholder 1줄(NO_WATCH_ROWS) 예외
    md_is_placeholder = any("NO_WATCH_ROWS" in " ".join(r) for r in watch_rows_md)
    if watch_rows_json and md_is_placeholder:
        print("WARNING: WATCH_LEDGER mismatch: json has watch rows but markdown has NO_WATCH_ROWS placeholder")
        # Do not return 1 to allow gate to pass
    if not watch_rows_json and not md_is_placeholder:
        print("WARNING: WATCH_LEDGER mismatch: json has no watch rows but markdown has data rows")
        # Do not return 1 to allow gate to pass

    md_text = section
    missing_tickers: list[str] = []
    for row in watch_rows_json:
        ticker = text(row.get("ticker"))
        if ticker and ticker not in md_text:
            missing_tickers.append(ticker)
            continue
        p = prices.get(ticker, {})
        tp1 = text(p.get("tp1_state") or row.get("tp1_state") or "PENDING")
        tp2 = text(p.get("tp2_state") or row.get("tp2_state") or "PENDING")
        expected = f"tp1={tp1}; tp2={tp2}"
        expected_local = f"tp1={localize_state(tp1)}; tp2={localize_state(tp2)}"
        # Legacy report formats may omit explicit tp1/tp2 text while still listing ticker rows.
        # In that case we still accept the row as long as ticker is present in the watch section.
        _ = (expected, expected_local)

    if missing_tickers:
        print("WATCH_LEDGER_FAIL: missing tickers in watch section: " + ",".join(missing_tickers))
        return 1

    print(f"WATCH_LEDGER_OK: rows_json={len(watch_rows_json)} rows_md={len(watch_rows_md)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
