#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STAGE 0B — AUDIT READ-ONLY (pendalaman)
=================================================
Melengkapi Stage 0 dengan:
  1. Profil 8 unit tanpa Content Block (64, 79, 80, 81, 82, 83, 84, 126).
  2. Pasangan teks identik (66-80) dan (68-79): konteks chapter induk.
  3. Integritas teks sumber + relasi section/chapter/content_blocks.
  4. Perbandingan teks ringkas (hash, panjang, awalan, akhiran, diff posisi).

TIDAK mengubah apa pun. Hanya membaca dump SQL.
"""

import hashlib
import os
import re
import sys

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")

TARGET_UNITS = [64, 79, 80, 81, 82, 83, 84, 126]
IDENTICAL_PAIRS = [(66, 80), (68, 79)]


# ----------------------------------------------------------------------
# Parser dump SQL (sama seperti Stage 0)
# ----------------------------------------------------------------------
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):
    if not t:
        return ""
    return re.sub(r"\s+", " ", t).strip()


def sha1(t):
    return hashlib.sha1(t.encode("utf-8")).hexdigest()


def count_words(t):
    return len(t.split()) if t else 0


def preview(t, n=120):
    t = norm(t)
    return t[:n] + ("..." if len(t) > n else "")


def tail(t, n=120):
    t = norm(t)
    return ("..." if len(t) > n else "") + t[-n:]


def main():
    with open(DUMP, "r", encoding="utf-8", errors="replace") as f:
        sql = f.read()

    books = parse_insert_rows(sql, "books")
    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")

    book_name = {to_int(b.get("id")): (b.get("nama_indonesia") or b.get("nama_arab") or "?") for b in books}
    chapter = {}
    for c in chapters:
        chapter[to_int(c.get("id"))] = {
            "book_id": to_int(c.get("book_id")),
            "judul": c.get("judul_indonesia") or c.get("judul_arab") or "?",
            "urutan": to_int(c.get("urutan")),
            "status": c.get("status"),
        }
    sec = {}
    for s in sections:
        sec[to_int(s.get("id"))] = {
            "chapter_id": to_int(s.get("chapter_id")),
            "parent_id": to_int(s.get("parent_id")) if s.get("parent_id") is not None else None,
            "urutan": to_int(s.get("urutan")),
            "tipe": s.get("tipe_bagian"),
            "judul": s.get("judul_indonesia") or s.get("judul_arab") or "?",
            "status": s.get("status"),
        }

    texts_by_section = {}
    for t in section_texts:
        texts_by_section.setdefault(to_int(t.get("section_id")), []).append(t)

    blocks_by_section = {}
    blocks_by_chapter = {}
    blocks_bab_direct = {}
    for b in blocks:
        cid = to_int(b.get("chapter_id"))
        blocks_by_chapter[cid] = blocks_by_chapter.get(cid, 0) + 1
        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

    def joined_text(sid):
        return "\n\n".join((r.get("teks_arab") or "") for r in texts_by_section.get(sid, []))

    print("=" * 84)
    print(" STAGE 0B — AUDIT READ-ONLY (profil unit, pasangan identik, integritas)")
    print("=" * 84)

    # ==================================================================
    # 1 & 2. PROFIL 8 UNIT TANPA CONTENT BLOCK
    # ==================================================================
    print("\n" + "#" * 84)
    print("# 1-2. PROFIL 8 UNIT TANPA CONTENT BLOCK")
    print("#" * 84)

    for sid in TARGET_UNITS:
        info = sec.get(sid)
        if info is None:
            print("\n  section_id=%s : TIDAK DITEMUKAN di tabel sections" % sid)
            continue
        cid = info["chapter_id"]
        ch = chapter.get(cid, {})
        rows = texts_by_section.get(sid, [])
        full = joined_text(sid)
        nf = norm(full)
        print("\n  ── section_id=%s ─────────────────────────────────────────────" % sid)
        print("     chapter_id      : %s (%s)" % (cid, ch.get("judul", "?")))
        print("     book_id         : %s (%s)" % (ch.get("book_id"), book_name.get(ch.get("book_id"), "?")))
        print("     judul section   : %s" % info["judul"])
        print("     tipe_bagian     : %s" % (info["tipe"] or "-"))
        print("     parent_id       : %s" % (info["parent_id"] if info["parent_id"] is not None else "NULL"))
        print("     urutan          : %s" % info["urutan"])
        print("     status section  : %s" % info["status"])
        print("     sumber teks     : section_texts (%d baris)" % len(rows))
        for r in rows:
            print("        text_id=%s page=%s jilid=%s block_no=%s src_ref=%s"
                  % (r.get("id"), r.get("page_number"), r.get("jilid"),
                     r.get("block_number"), r.get("source_reference")))
        print("     jumlah karakter : %d (mentah) / %d (setelah normalisasi spasi)" % (len(full), len(nf)))
        print("     jumlah kata     : %d" % count_words(nf))
        print("     status CB       : blok section=%d | blok BAB-direct chapter=%d | total blok chapter=%d"
              % (blocks_by_section.get(sid, 0), blocks_bab_direct.get(cid, 0), blocks_by_chapter.get(cid, 0)))
        print("     awalan          : %s" % preview(full, 140))
        print("     akhiran         : %s" % tail(full, 140))

    # ==================================================================
    # 3. PASANGAN TEKS IDENTIK
    # ==================================================================
    print("\n" + "#" * 84)
    print("# 3. PASANGAN TEKS IDENTIK — KONTEKS CHAPTER INDUK")
    print("#" * 84)

    for a, b in IDENTICAL_PAIRS:
        print("\n  ══ PASANGAN (%s, %s) ══════════════════════════════════════" % (a, b))
        for sid in (a, b):
            info = sec.get(sid, {})
            cid = info.get("chapter_id")
            ch = chapter.get(cid, {})
            rows = texts_by_section.get(sid, [])
            full = joined_text(sid)
            nf = norm(full)
            print("\n     section_id=%s" % sid)
            print("        chapter induk : #%s \"%s\" (book #%s: %s)"
                  % (cid, ch.get("judul", "?"), ch.get("book_id"), book_name.get(ch.get("book_id"), "?")))
            print("        chapter urutan: %s | status: %s" % (ch.get("urutan"), ch.get("status")))
            print("        judul section : %s" % info.get("judul", "?"))
            print("        tipe_bagian   : %s" % (info.get("tipe") or "-"))
            print("        parent_id     : %s" % (info.get("parent_id") if info.get("parent_id") is not None else "NULL"))
            print("        urutan        : %s | status: %s" % (info.get("urutan"), info.get("status")))
            print("        sumber teks   : section_texts (%d baris)" % len(rows))
            for r in rows:
                print("           text_id=%s page=%s block_no=%s src_ref=%s"
                      % (r.get("id"), r.get("page_number"), r.get("block_number"), r.get("source_reference")))
            print("        karakter      : %d | kata: %d" % (len(nf), count_words(nf)))
            print("        sha1          : %s" % sha1(nf))
            print("        blok section  : %d" % blocks_by_section.get(sid, 0))
            print("        awalan        : %s" % preview(full, 140))
            print("        akhiran       : %s" % tail(full, 140))

        # perbandingan
        ta, tb = norm(joined_text(a)), norm(joined_text(b))
        print("\n     ── PERBANDINGAN ──")
        print("        sha1 sama?          : %s" % ("YA (identik byte-per-byte setelah normalisasi spasi)" if sha1(ta) == sha1(tb) else "TIDAK"))
        print("        panjang char        : %d vs %d (selisih %d)" % (len(ta), len(tb), abs(len(ta) - len(tb))))
        print("        jumlah kata         : %d vs %d (selisih %d)" % (count_words(ta), count_words(tb), abs(count_words(ta) - count_words(tb))))
        if ta == tb:
            print("        hasil               : 100%% IDENTIK setelah normalisasi spasi")
        else:
            # cari titik beda pertama
            limit = min(len(ta), len(tb))
            diff_at = None
            for i in range(limit):
                if ta[i] != tb[i]:
                    diff_at = i
                    break
            if diff_at is None:
                diff_at = limit
            print("        titik beda pertama  : posisi %d" % diff_at)
            print("           A: ...%s" % ta[max(0, diff_at - 40):diff_at + 60])
            print("           B: ...%s" % tb[max(0, diff_at - 40):diff_at + 60])

    # ==================================================================
    # 4. INTEGRITAS TEKS & RELASI STRUKTUR
    # ==================================================================
    print("\n" + "#" * 84)
    print("# 4. INTEGRITAS TEKS SUMBER & RELASI STRUKTUR")
    print("#" * 84)

    # 4a. section_texts tanpa section valid
    print("\n  4a. section_texts dengan section_id tidak valid:")
    orphan_texts = [t for t in section_texts if to_int(t.get("section_id")) not in sec]
    if not orphan_texts:
        print("      Jumlah temuan: 0 (semua section_texts menunjuk section yang ada).")
    else:
        print("      Jumlah temuan: %d" % len(orphan_texts))
        for t in orphan_texts:
            print("         text_id=%s section_id=%s" % (t.get("id"), t.get("section_id")))

    # 4b. sections tanpa chapter valid
    print("\n  4b. sections dengan chapter_id tidak valid:")
    orphan_sections = [s for s in sections if to_int(s.get("chapter_id")) not in chapter]
    if not orphan_sections:
        print("      Jumlah temuan: 0 (semua sections menunjuk chapter yang ada).")
    else:
        print("      Jumlah temuan: %d" % len(orphan_sections))
        for s in orphan_sections:
            print("         section_id=%s chapter_id=%s" % (s.get("id"), s.get("chapter_id")))

    # 4c. content_blocks dengan relasi tidak konsisten
    print("\n  4c. content_blocks dengan relasi tidak konsisten:")
    bad_blocks = []
    for b in blocks:
        cid = to_int(b.get("chapter_id"))
        sid = b.get("section_id")
        bid = to_int(b.get("book_id"))
        reason = None
        if cid not in chapter:
            reason = "chapter_id tidak ada"
        elif sid is not None:
            sid_i = to_int(sid)
            if sid_i not in sec:
                reason = "section_id tidak ada"
            elif sec[sid_i]["chapter_id"] != cid:
                reason = "section_id milik chapter lain (%s)" % sec[sid_i]["chapter_id"]
        if reason is None and cid in chapter and chapter[cid]["book_id"] != bid:
            reason = "book_id tidak cocok dengan chapter (book chapter=%s)" % chapter[cid]["book_id"]
        if reason:
            bad_blocks.append((b, reason))
    if not bad_blocks:
        print("      Jumlah temuan: 0 (semua content_blocks konsisten).")
    else:
        print("      Jumlah temuan: %d" % len(bad_blocks))
        for b, reason in bad_blocks[:50]:
            print("         block_id=%s chapter=%s section=%s book=%s -> %s"
                  % (b.get("id"), b.get("chapter_id"), b.get("section_id"), b.get("book_id"), reason))
        if len(bad_blocks) > 50:
            print("         ... dan %d lainnya" % (len(bad_blocks) - 50))

    # 4d. section_texts kosong / whitespace saja
    print("\n  4d. section_texts kosong atau hanya whitespace:")
    empty_texts = [t for t in section_texts if not norm(t.get("teks_arab"))]
    if not empty_texts:
        print("      Jumlah temuan: 0 (semua section_texts berisi teks).")
    else:
        print("      Jumlah temuan: %d" % len(empty_texts))
        for t in empty_texts:
            print("         text_id=%s section_id=%s" % (t.get("id"), t.get("section_id")))

    # 4e. content_blocks dengan text_arab kosong
    print("\n  4e. content_blocks dengan text_arab kosong:")
    empty_blocks = [b for b in blocks if not norm(b.get("text_arab"))]
    if not empty_blocks:
        print("      Jumlah temuan: 0 (semua blok berisi teks).")
    else:
        print("      Jumlah temuan: %d" % len(empty_blocks))
        for b in empty_blocks[:30]:
            print("         block_id=%s chapter=%s section=%s type=%s"
                  % (b.get("id"), b.get("chapter_id"), b.get("section_id"), b.get("block_type")))

    # 4f. section container BAB (tipe_bagian='bab') vs blok BAB-direct
    print("\n  4f. Section container BAB (tipe_bagian='bab') — konsistensi blok BAB-direct:")
    containers = [(sid, v) for sid, v in sec.items() if (v.get("tipe") or "") == "bab"]
    if not containers:
        print("      Tidak ada section bertipe 'bab'.")
    else:
        for sid, v in sorted(containers, key=lambda x: x[0]):
            cid = v["chapter_id"]
            n_text = len(texts_by_section.get(sid, []))
            print("      section_id=%-4s chapter #%-3s \"%-28s\" | teks=%d | blok_direct_chapter=%d | blok_section=%d"
                  % (sid, cid, v["judul"][:28], n_text,
                     blocks_bab_direct.get(cid, 0), blocks_by_section.get(sid, 0)))

    # 4g. chapter tanpa section sama sekali
    print("\n  4g. Chapter tanpa section (tidak bisa punya teks/blok):")
    chapters_with_sections = set(v["chapter_id"] for v in sec.values())
    empty_chapters = [cid for cid in chapter if cid not in chapters_with_sections]
    if not empty_chapters:
        print("      Jumlah temuan: 0.")
    else:
        for cid in sorted(empty_chapters):
            print("      chapter #%s \"%s\" — 0 section, 0 teks, %d blok"
                  % (cid, chapter[cid]["judul"], blocks_by_chapter.get(cid, 0)))

    # ==================================================================
    # 5. RINGKASAN
    # ==================================================================
    print("\n" + "=" * 84)
    print(" RINGKASAN STAGE 0B")
    print("=" * 84)
    print("  8 unit diperiksa          : %d" % len(TARGET_UNITS))
    print("  Pasangan identik diperiksa: %d" % len(IDENTICAL_PAIRS))
    print("  section_texts orphan      : %d" % len(orphan_texts))
    print("  sections orphan           : %d" % len(orphan_sections))
    print("  content_blocks inkonsisten: %d" % len(bad_blocks))
    print("  section_texts kosong      : %d" % len(empty_texts))
    print("  content_blocks kosong     : %d" % len(empty_blocks))
    print("=" * 84)
    return 0


if __name__ == "__main__":
    sys.exit(main())
