#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STAGE 0 — DETAIL READ-ONLY (pendalaman)
=================================================
Melengkapi audit dengan:
  A. Isi teks tiap pasangan subbab duplikat (cek tumpang tindih nyata).
  B. Status tipe_bagian untuk unit "tanpa blok" (container BAB vs subbab asli).
  C. Cek apakah blok BAB-direct (section_id NULL) ada untuk chapter terkait.
  D. Cek duplikasi teks identik antar subbab (bukan hanya urutan).
Read-only, hanya membaca dump.
"""

import os
import re
import sys

# Paksa output UTF-8 agar teks Arab tidak memicu UnicodeEncodeError di konsol Windows.
try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

DUMP = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "manuputr_perpus_kitab.sql")


def parse_insert_rows(sql, table):
    rows = []
    pattern = re.compile(
        r"INSERT\s+INTO\s+`" + re.escape(table) + r"`\s*\(([^)]*)\)\s*VALUES\s*",
        re.IGNORECASE,
    )
    for m in pattern.finditer(sql):
        cols = [c.strip().strip("`") for c in m.group(1).split(",")]
        for tup in parse_value_tuples(sql, m.end()):
            if len(tup) == len(cols):
                rows.append(dict(zip(cols, tup)))
    return rows


def parse_value_tuples(s, pos):
    n = len(s)
    tuples = []
    i = pos
    while i < n and s[i].isspace():
        i += 1
    while i < n and s[i] == "(":
        i += 1
        values, buf = [], []
        in_str = escaped = False
        while i < n:
            ch = s[i]
            if in_str:
                if escaped:
                    mapping = {"n": "\n", "r": "\r", "t": "\t", "0": "\0",
                               "\\": "\\", "'": "'", '"': '"', "Z": "\x1a"}
                    buf.append(mapping.get(ch, ch))
                    escaped = False
                    i += 1
                    continue
                if ch == "\\":
                    escaped = True
                    i += 1
                    continue
                if ch == "'":
                    if i + 1 < n and s[i + 1] == "'":
                        buf.append("'")
                        i += 2
                        continue
                    in_str = False
                    i += 1
                    continue
                buf.append(ch)
                i += 1
                continue
            if ch == "'":
                in_str = True
                i += 1
                continue
            if ch == ",":
                values.append(finalize("".join(buf)))
                buf = []
                i += 1
                continue
            if ch == ")":
                values.append(finalize("".join(buf)))
                i += 1
                break
            if ch.isspace():
                i += 1
                continue
            buf.append(ch)
            i += 1
        tuples.append(values)
        while i < n and (s[i].isspace() or s[i] == ","):
            i += 1
        if i >= n or s[i] != "(":
            break
    return tuples


def finalize(raw):
    t = raw.strip()
    return None if t.upper() == "NULL" else t


def to_int(v):
    try:
        return int(v)
    except (TypeError, ValueError):
        return None


def norm(t):
    """Normalisasi ringan untuk cek tumpang tindih teks."""
    if not t:
        return ""
    t = re.sub(r"\s+", " ", t)
    return t.strip()


def main():
    with open(DUMP, "r", encoding="utf-8", errors="replace") as f:
        sql = f.read()

    chapters = parse_insert_rows(sql, "chapters")
    sections = parse_insert_rows(sql, "sections")
    section_texts = parse_insert_rows(sql, "section_texts")
    blocks = parse_insert_rows(sql, "content_blocks")

    chapter_name = {to_int(c.get("id")): (c.get("judul_indonesia") or c.get("judul_arab") or "?") for c in chapters}
    sec = {}
    for s in sections:
        sec[to_int(s.get("id"))] = {
            "chapter_id": to_int(s.get("chapter_id")),
            "urutan": to_int(s.get("urutan")),
            "tipe": s.get("tipe_bagian"),
            "judul": s.get("judul_indonesia") or s.get("judul_arab") or "?",
        }

    texts_by_section = {}
    for t in section_texts:
        sid = to_int(t.get("section_id"))
        texts_by_section.setdefault(sid, []).append(t)

    blocks_by_section = {}
    blocks_bab_direct = {}
    for b in blocks:
        cid = to_int(b.get("chapter_id"))
        if b.get("section_id") is None:
            blocks_bab_direct[cid] = blocks_bab_direct.get(cid, 0) + 1
        else:
            sid = to_int(b.get("section_id"))
            blocks_by_section[sid] = blocks_by_section.get(sid, 0) + 1

    print("=" * 70)
    print(" STAGE 0 — DETAIL READ-ONLY")
    print("=" * 70)

    # ---------------------------------------------------------------
    # A. Pasangan subbab duplikat: cek tumpang tindih teks
    # ---------------------------------------------------------------
    print("\n### A. ISI TEKS PASANGAN SUBBAB DUPLIKAT (cek tumpang tindih)\n")
    pairs = [(48, 61, 62), (55, 67, 69), (61, 80, 81), (62, 82, 83)]
    for cid, s1, s2 in pairs:
        print("Chapter #%s (%s) — urutan sama" % (cid, chapter_name.get(cid, "?")))
        for sid in (s1, s2):
            info = sec.get(sid, {})
            rows = texts_by_section.get(sid, [])
            total_len = sum(len(norm(r.get("teks_arab"))) for r in rows)
            print("  section_id=%s \"%s\" tipe=%s | %d baris teks | total %d char | blok=%d"
                  % (sid, info.get("judul", "?"), info.get("tipe") or "-",
                     len(rows), total_len, blocks_by_section.get(sid, 0)))
            for r in rows:
                pv = norm(r.get("teks_arab"))[:90]
                print("      text_id=%s page=%s block_no=%s : \"%s...\""
                      % (r.get("id"), r.get("page_number"), r.get("block_number"), pv))
        # cek tumpang tindih
        t1 = " ".join(norm(r.get("teks_arab")) for r in texts_by_section.get(s1, []))
        t2 = " ".join(norm(r.get("teks_arab")) for r in texts_by_section.get(s2, []))
        if t1 and t2:
            if t1 == t2:
                verdict = "IDENTIK (100% sama)"
            elif t1 in t2 or t2 in t1:
                verdict = "TUMPANG TINDIH (salah satu memuat yang lain)"
            else:
                # cek irisan kata
                w1, w2 = set(t1.split()), set(t2.split())
                inter = len(w1 & w2)
                union = len(w1 | w2) or 1
                verdict = "irisan kata %.1f%% (%d kata sama)" % (100.0 * inter / union, inter)
            print("  -> VERDICT: %s" % verdict)
        else:
            print("  -> VERDICT: salah satu kosong")
        print()

    # ---------------------------------------------------------------
    # B. Unit tanpa blok: container BAB vs subbab asli
    # ---------------------------------------------------------------
    print("### B. UNIT TANPA BLOK — TIPE & KONTEKS\n")
    missing = []
    for sid, rows in texts_by_section.items():
        if sid not in blocks_by_section:
            missing.append(sid)
    for sid in sorted(missing, key=lambda x: (x is None, x)):
        info = sec.get(sid, {})
        cid = info.get("chapter_id")
        rows = texts_by_section.get(sid, [])
        print("  section_id=%s | chapter #%s (%s) | tipe=%s | \"%s\""
              % (sid, cid, chapter_name.get(cid, "?"), info.get("tipe") or "-", info.get("judul", "?")))
        print("      baris teks=%d | blok subbab=%d | blok BAB-direct chapter=%d"
              % (len(rows), blocks_by_section.get(sid, 0), blocks_bab_direct.get(cid, 0)))
        for r in rows:
            pv = norm(r.get("teks_arab"))[:100]
            print("      text_id=%s page=%s : \"%s...\"" % (r.get("id"), r.get("page_number"), pv))
    print()

    # ---------------------------------------------------------------
    # C. Rekap blok per chapter (BAB-direct vs subbab)
    # ---------------------------------------------------------------
    print("### C. REKAP BLOK PER CHAPTER\n")
    all_cids = sorted(set(list(chapter_name.keys())))
    for cid in all_cids:
        n_direct = blocks_bab_direct.get(cid, 0)
        subs = [s for s in sec.values() if s["chapter_id"] == cid]
        n_sub_blocks = sum(blocks_by_section.get(sid, 0) for sid in
                           [k for k, v in sec.items() if v["chapter_id"] == cid])
        n_texts = sum(len(texts_by_section.get(sid, [])) for sid in
                      [k for k, v in sec.items() if v["chapter_id"] == cid])
        print("  chapter #%-3s %-32s | sections=%d | texts=%d | blok_direct=%d | blok_subbab=%d"
              % (cid, chapter_name.get(cid, "?")[:32], len(subs), n_texts, n_direct, n_sub_blocks))
    print()

    # ---------------------------------------------------------------
    # D. Duplikasi teks identik antar subbab (lintas chapter)
    # ---------------------------------------------------------------
    print("### D. TEKS IDENTIK ANTAR SUBBAB (deteksi duplikasi nyata)\n")
    sig = {}
    for sid, rows in texts_by_section.items():
        joined = " ".join(norm(r.get("teks_arab")) for r in rows)
        if not joined:
            continue
        sig.setdefault(joined, []).append(sid)
    found = False
    for joined, sids in sig.items():
        if len(sids) > 1:
            found = True
            print("  Teks identik pada section: %s" % sids)
            for sid in sids:
                info = sec.get(sid, {})
                print("      section_id=%s chapter #%s \"%s\" tipe=%s"
                      % (sid, info.get("chapter_id"), info.get("judul", "?"), info.get("tipe") or "-"))
            print("      preview: \"%s...\"" % joined[:100])
    if not found:
        print("  Jumlah temuan: 0 (tidak ada teks identik antar subbab).")
    print()
    print("=" * 70)
    return 0


if __name__ == "__main__":
    sys.exit(main())
