"""격리 검증 — 뉴파워트럭 15톤 덤프 타이어 2행(11/30) · 임시 MariaDB(<임시 DB> · 운영 사본 · 360 사진 표 3 · 원본 응답 표 1 은 빈 표)
  S1 지금 코드 + 지금 DB → 기준(대기 1 · 기존 1 = 운영 11/30 01:00 과 같음)
  S2 계획 연습(--rehearse) → 저장(--commit) · 둘 다 --strict
  S3 옛 코드 + 바뀐 DB → (코드를 같이 안 바꾸면) 무엇이 검토로 올라오는지
  S4 새 코드 + 바뀐 DB → 검토 0 · 저장 대상 0
  S5 새로 받기(ZA01 가격표 · 카탈로그 · 제원) → 새 코드 --commit 두 번 → 장부의 두 항목 풀림 · 다시 안 올라옴 · 저장 0
  S6 엑시언트(ZC01) — 옛 코드 = 새 코드(기존 39 · 저장 0)
  S7 되돌리기 SQL → 바뀐 두 표가 처음과 같음(CHECKSUM) · 다시 계획 저장(운영 반영 때와 같은 상태로 끝냄은 안 함 — 끝 상태 = 처음)
  실행: cd ~/work/za01_tire_20261130/iso && python3 iso_run.py   (결과 iso_run.json · iso_run.log)"""
import glob, json, os, shutil, subprocess, sys, time
from pathlib import Path

I = Path(__file__).resolve().parent; W = I.parent; SB = I / "sb"
LIVE, NEW = Path("<운영 트리>"), W / "tree"
DAY = Path("<운영 트리>/output/logs/new_car_load_20261130_010002/collect/hmc_cv/20261130")
PLAN = W / "plan_za01_tire.json"
M = ["mysql", "--no-defaults", "-S", str(I / "db.sock"), "-u", "kay", "-N", "cars_app"]
ENV = dict(os.environ, KAY_ENV_FILE=str(I / "iso.env"), KAY_OUTPUT_ROOT=str(SB / "output"), KAY_LOG_ROOT=str(SB / "logs"),
           KAY_HMC_RELOAD_ROOT=str(SB / "reload"), KAY_KIA_PIP_ROOT=str(SB / "kia_pip"), KAY_YEAR_AUDIT_ROOT=str(SB / "year_audit"),
           KAY_COLLECT_ROOT=str(SB / "collect"), KAY_BACKUP_ROOT=str(SB / "backups"), KAY_WEB_ROOT=str(SB / "web"), KAY_STATUS_HOOK="")
LOG = open(I / "iso_run.log", "a", encoding="utf-8")
RES, FAIL = {}, []


def say(*a):
    s = " ".join(str(x) for x in a)
    print(s, flush=True); LOG.write(s + "\n"); LOG.flush()


def sql(q):
    return subprocess.check_output(M + ["-e", q]).decode().strip()


def run(tree, args, tag):
    t0 = time.time()
    r = subprocess.run(["nice", "-n", "15", str(LIVE / ".venv/bin/python"), *args], cwd=tree, env=dict(ENV, PYTHONPATH=str(tree)),
                       capture_output=True, text=True, timeout=1800)
    (SB / f"{tag}.out").write_text(r.stdout + "\n--- stderr ---\n" + r.stderr)
    say(f"  [{tag}] 종료 {r.returncode} · {time.time() - t0:.0f}초 · " + " / ".join(l for l in r.stdout.splitlines() if l.startswith("■"))[:300])
    return r


def sync(tree, cc, tag, day=DAY, commit=False):
    out = SB / "plans" / tag
    out.mkdir(parents=True, exist_ok=True)
    r = run(tree, ["hyundai/hmc_cv_sync.py", f"--dir={day}", f"--out={out}", cc] + (["--commit"] if commit else []), tag)
    f = sorted(out.glob(f"{cc}_*.json"))
    d = json.loads(f[-1].read_text()) if f else {}
    items = [{k: i.get(k) for k in ("kind", "id", "action", "label")} for i in d.get("items") or []]
    return {"rc": r.returncode, "state": d.get("state"), "counts": d.get("counts"), "items": items, "fail": d.get("fail")}


def check(name, ok, got):
    say(("  통과 " if ok else "  실패 ") + name + f" — {json.dumps(got, ensure_ascii=False, default=str)[:400]}")
    RES[name] = {"ok": bool(ok), "got": got}
    if not ok:
        FAIL.append(name)


def trim_rows():
    return sql("SELECT id, basic_option_code, basic_option_name FROM options_basic WHERE sale_model_code='ZA01PDF64DA0B96A' AND basic_option_name LIKE '%타이어%' ORDER BY id")


def sums():
    return sql("CHECKSUM TABLE options_basic, model_change_logs")


def ledger(cc="ZA01"):
    s = json.loads((SB / "logs" / "hmc_cv_sync_state.json").read_text())
    return {k: {"ack": v.get("ack"), "label": (v.get("label") or "")[:12]} for k, v in s["cars"][cc]["review"].items()}


say(f"=== {time.strftime('%F %T')} 격리 검증 시작 · DB @@port {sql('SELECT @@port')} · 계획 {PLAN.name}")
assert sql("SELECT @@port") == "3399"
base_sum, base_rows = sums(), trim_rows()
say("기준 행:\n" + base_rows)

s1 = sync(LIVE, "ZA01", "S1_old_before")
check("S1 지금 코드 + 지금 DB = 운영 01:00 과 같음(검토 대기 1 · 기존 1 · 저장 0)",
      s1["state"] == "user_check" and s1["counts"]["review_known"] == 2 and s1["counts"]["auto"] == 0 and {i["id"] for i in s1["items"]} == {"a323180b682d", "283ec3719e6b"}, s1)

r = run(NEW, ["common/consistency_fix.py", f"--plan={PLAN}", "--rehearse", "--strict"], "S2_rehearse")
check("S2a 연습 — 처음과 같음 · 바꾼 뒤 되돌림", r.returncode == 0 and trim_rows() == base_rows and sums() == base_sum, r.stdout[-600:])
r = run(NEW, ["common/consistency_fix.py", f"--plan={PLAN}", "--commit", "--strict"], "S2_commit")
after_rows = trim_rows()
check("S2b 저장 — 두 행 id 그대로 · 이름 · 코드 = 계획", r.returncode == 0 and after_rows.splitlines() == [
    "1212149\tZADC1DDE94FD\t전축 타이어 12R(러그)", "1212150\tZAA6C1AEA091\t후축 타이어 12R(러그)"], after_rows)
rb = sorted(glob.glob(str(SB / "backups" / "**" / "rollback_consistency_fix_*.sql"), recursive=True))
check("S2c 되돌리기 SQL 하나 생김(격리 백업 폴더)", len(rb) == 1, rb)

s3 = sync(LIVE, "ZA01", "S3_old_after")
check("S3 옛 코드 + 바뀐 DB — 코드를 안 바꾸면 새 이름 2행이 «원본에 없음»으로 다시 올라옴(같이 반영해야 하는 까닭)",
      s3["counts"]["auto"] == 0 and sum(i["kind"] == "gone_row" for i in s3["items"]) == 2, s3)

s4 = sync(NEW, "ZA01", "S4_new_after")
check("S4 새 코드 + 바뀐 DB — 검토 0 · 저장 대상 0 · complete", s4["state"] == "complete" and not s4["items"] and s4["counts"]["auto"] == 0, s4)

r = run(NEW, ["hyundai/hyundai_reload.py", "--collect", "ZA01", "ZC01"], "S5_collect")
days = sorted((SB / "reload").glob("[0-9]" * 8))
pdfs = sorted(glob.glob(str(days[-1] / "commercial-pdf/ZA01/pdf/*.pdf"))) if days else []
shas = {Path(p).name: __import__("hashlib").sha256(Path(p).read_bytes()).hexdigest()[:16] for p in pdfs}
check("S5a 새로 받기 — 가격표 내용 지문 = 11/30 01:00 판(5e8d0239f6984e0c)", r.returncode == 0 and "5e8d0239f6984e0c" in shas.values(), shas)
s5 = sync(NEW, "ZA01", "S5_commit1", day=days[-1] if days else DAY, commit=True)
led = ledger()
check("S5b 새로 받은 판 + 새 코드 --commit — 저장 0 · complete · 장부 두 항목 풀림", s5["state"] == "complete" and s5["counts"]["saved"] == 0
      and s5["counts"]["resolved"] == 2 and not ({"a323180b682d", "283ec3719e6b"} & set(led)), {"sync": s5, "ledger": led})
s5b = sync(NEW, "ZA01", "S5_commit2", day=days[-1] if days else DAY, commit=True)
check("S5c 한 번 더 — 같은 두 행이 검토로 다시 안 올라옴", s5b["state"] == "complete" and not s5b["items"] and s5b["counts"]["saved"] == 0, s5b)
check("S5d 저장 실행 두 번 뒤에도 두 행 그대로", trim_rows() == after_rows, trim_rows())

o6, n6 = sync(LIVE, "ZC01", "S6_old_zc01", day=days[-1]), sync(NEW, "ZC01", "S6_new_zc01", day=days[-1])
check("S6 엑시언트 — 옛 코드 = 새 코드(상태 · 수 · 항목)", (o6["state"], o6["counts"], o6["items"]) == (n6["state"], n6["counts"], n6["items"])
      and n6["counts"]["auto"] == 0, {"old": [o6["state"], o6["counts"]], "new": [n6["state"], n6["counts"]]})

if rb:
    subprocess.run(M + ["-e", f"source {rb[0]}"], check=True)
check("S7 되돌리기 SQL → options_basic · model_change_logs 가 처음과 같음", sums() == base_sum and trim_rows() == base_rows, {"sum": sums(), "rows": trim_rows()})

say(f"=== 끝 — 통과 {sum(v['ok'] for v in RES.values())} · 실패 {len(FAIL)} {FAIL}")
(I / "iso_run.json").write_text(json.dumps({"at": time.strftime("%F %T"), "plan_sha256": __import__("hashlib").sha256(PLAN.read_bytes()).hexdigest(),
                                            "results": RES, "fail": FAIL}, ensure_ascii=False, indent=1, default=str))
sys.exit(1 if FAIL else 0)
