#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Stage 0C — READ-ONLY audit (no DB connection, no writes).

Tujuan: memverifikasi kondisi data section container BAB (63, 65, 68, 177, 178)
untuk menilai dampak jika generator dijalankan ulang pada section 65 dan 68.

Sumber data: dump SQL manuputr_perpus_kitab.sql (read-only).
"""

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")
DUMP = os.path.normpath(DUMP)

TARGET_SECTIONS = [63, 65, 68, 177, 178]


def read_dump(path):
    with open(path, "r", encoding="utf-8", errors="replace") as f:
        return f.read()


def parse_value_tuples(s, pos):
    """Parse consecutive ( ... ), ( ... ) tuples starting at pos."""
    rows = []
    n = len(s)
    while pos < n:
        while pos < n and s[pos] in " \t\r\n,":
            pos += 1
        if pos >= n or s[pos] != "(":
            break
        pos += 1
        fields = []
        cur = []
        in_str = False
        while pos < n:
            ch = s[pos]
            if in_str:
                if ch == "\\":
                    nxt = s[pos + 1] if pos + 1 < n else ""
                    mapping = {"n": "\n", "r": "\r", "t": "\t", "0": "\0",
                               "\\": "\\", "'": "'", '"': '"', "Z": "\x1a"}
                    cur.append(mapping.get(nxt, nxt))
                    pos += 2
                    continue
                if ch == "'":
                    if pos + 1 < n and s[pos + 1] == "'":
                        cur.append("'")
                        pos += 2
                        continue
                    in_str = False
                    pos += 1
                    continue
                cur.append(ch)
                pos += 1
                continue
            if ch == "'":
                in_str = True
                pos += 1
                continue
            if ch == ",":
                fields.append("".join(cur))
                cur = []
                pos += 1
                continue
            if ch == ")":
                fields.append("".join(cur))
                pos += 1
                rows.append(fields)
                break
            cur.append(ch)
            pos += 1
        else:
            break
    return rows, pos


def parse_insert_rows(sql, table):
    pattern = re.compile(r"INSERT\s+INTO\s+`?" + re.escape(table) + r"`?\s*\(([^)]*)\)\s*VALUES\s*", re.IGNORECASE)
    out = []
    for m in pattern.finditer(sql):
        cols = [c.strip().strip("`") for c in m.group(1).split(",")]
        rows, _ = parse_value_tuples(sql, m.end())
        for r in rows:
            if len(r) != len(cols):
                continue
            out.append({c: (v.strip() if isinstance(v, str) else v)
                        for c, v in zip(cols, r)})
    return out


def to_int(v):
    try:
        return int(str(v).strip())
    except Exception:
        return None


def is_null(v):
    return v is None or str(v).strip().upper() == "NULL"


def main():
    sql = read_dump(DUMP)

    chapters = parse_insert_rows(sql, "chapters")
    sections = parse_insert_rows(sql, "sections")
    texts = parse_insert_rows(sql, "section_texts")
    blocks = parse_insert_rows(sql, "content_blocks")

    chapter_by_id = {to_int(c.get("id")): c for c in chapters}

    print("=" * 78)
    print("STAGE 0C — VERIFIKASI DATA CONTAINER BAB (READ-ONLY)")
    print("=" * 78)
    print("chapters=%d sections=%d section_texts=%d content_blocks=%d"
          % (len(chapters), len(sections), len(texts), len(blocks)))

    # ---------------------------------------------------------------
    # 1) Profil tiap section target
    # ---------------------------------------------------------------
    print("\n" + "-" * 78)
    print("1) PROFIL SECTION TARGET")
    print("-" * 78)
    print("%-6s %-8s %-6s %-8s %-8s %-10s %-8s" %
          ("sec", "chapter", "tipe", "texts", "chars", "cb_total", "cb_null"))

    sec_by_id = {}
    for s in sections:
        sid = to_int(s.get("id"))
        sec_by_id[sid] = s

    for sid in TARGET_SECTIONS:
        s = sec_by_id.get(sid)
        if s is None:
            print("%-6d TIDAK DITEMUKAN" % sid)
            continue
        cid = to_int(s.get("chapter_id"))
        tipe = s.get("tipe_bagian", "?")
        trows = [t for t in texts if to_int(t.get("section_id")) == sid]
        chars = sum(len(t.get("teks_arab", "") or "") for t in trows)
        brows = [b for b in blocks if to_int(b.get("section_id")) == sid]
        bnull = [b for b in blocks if to_int(b.get("chapter_id")) == cid and is_null(b.get("section_id"))]
        print("%-6d %-8s %-6s %-8d %-8d %-10d %-8d" %
              (sid, cid, tipe, len(trows), chars, len(brows), len(bnull)))

    # ---------------------------------------------------------------
    # 2) Apakah chapter punya SUBBAB asli (selain container)?
    # ---------------------------------------------------------------
    print("\n" + "-" * 78)
    print("2) STRUKTUR CHAPTER PEMILIK (apakah ada SUBBAB asli?)")
    print("-" * 78)
    for sid in TARGET_SECTIONS:
        s = sec_by_id.get(sid)
        if s is None:
            continue
        cid = to_int(s.get("chapter_id"))
        ch = chapter_by_id.get(cid, {})
        all_secs = [x for x in sections if to_int(x.get("chapter_id")) == cid]
        real = [x for x in all_secs if str(x.get("tipe_bagian", "")) != "bab"]
        containers = [x for x in all_secs if str(x.get("tipe_bagian", "")) == "bab"]
        print("\n  section %d -> chapter %d (%s)" %
              (sid, cid, ch.get("judul_indonesia") or ch.get("judul_arab") or "?"))
        print("    total sections=%d | container bab=%d | subbab asli=%d"
              % (len(all_secs), len(containers), len(real)))
        print("    container ids=%s" % [to_int(x.get("id")) for x in containers])
        print("    subbab asli ids=%s" % [to_int(x.get("id")) for x in real])

    # ---------------------------------------------------------------
    # 3) Blok per section: distribusi sort_order & duplikasi potensial
    # ---------------------------------------------------------------
    print("\n" + "-" * 78)
    print("3) DISTRIBUSI BLOK PADA SECTION 65 & 68")
    print("-" * 78)
    for sid in (65, 68):
        brows = [b for b in blocks if to_int(b.get("section_id")) == sid]
        if not brows:
            print("\n  section %d: tidak ada blok" % sid)
            continue
        orders = [to_int(b.get("sort_order")) for b in brows]
        orders = [o for o in orders if o is not None]
        dup = len(orders) - len(set(orders))
        print("\n  section %d: %d blok | sort_order min=%s max=%s | duplikat sort_order=%d"
              % (sid, len(brows), min(orders) if orders else "-",
                 max(orders) if orders else "-", dup))
        types = {}
        for b in brows:
            t = b.get("block_type", "?")
            types[t] = types.get(t, 0) + 1
        print("    block_type: %s" % types)
        pages = [to_int(b.get("page_start")) for b in brows if not is_null(b.get("page_start"))]
        print("    page_start: %s..%s (%d blok berhalaman)"
              % (min(pages) if pages else "-", max(pages) if pages else "-", len(pages)))

    # ---------------------------------------------------------------
    # 4) Bandingkan teks container vs blok yang tersimpan (section_id=ID)
    # ---------------------------------------------------------------
    print("\n" + "-" * 78)
    print("4) KESESUAIAN TEKS SUMBER vs BLOK TERSIMPAN (section 65 & 68)")
    print("-" * 78)
    for sid in (65, 68):
        trows = [t for t in texts if to_int(t.get("section_id")) == sid]
        src = "\n".join((t.get("teks_arab") or "") for t in trows)
        brows = [b for b in blocks if to_int(b.get("section_id")) == sid]
        joined = "\n".join((b.get("text_arab") or "") for b in brows)
        src_words = len(src.split())
        blk_words = len(joined.split())
        print("\n  section %d:" % sid)
        print("    teks sumber : %d baris, %d chars, %d kata"
              % (len(trows), len(src), src_words))
        print("    blok gabung : %d blok, %d chars, %d kata"
              % (len(brows), len(joined), blk_words))
        if src_words > 0:
            print("    rasio kata blok/sumber = %.2f" % (blk_words / src_words))

    # ---------------------------------------------------------------
    # 5) Blok BAB-direct (section_id NULL) pada chapter 65 & 68
    # ---------------------------------------------------------------
    print("\n" + "-" * 78)
    print("5) BLOK BAB-DIRECT (section_id IS NULL) PADA CHAPTER PEMILIK")
    print("-" * 78)
    for sid in (65, 68):
        s = sec_by_id.get(sid)
        if s is None:
            continue
        cid = to_int(s.get("chapter_id"))
        bnull = [b for b in blocks if to_int(b.get("chapter_id")) == cid and is_null(b.get("section_id"))]
        print("  chapter %d (container %d): %d blok BAB-direct" % (cid, sid, len(bnull)))

    # ---------------------------------------------------------------
    # 6) Section container lain yang punya blok section_id=ID (pola global)
    # ---------------------------------------------------------------
    print("\n" + "-" * 78)
    print("6) POLA GLOBAL: container BAB yang menyimpan blok dengan section_id=ID")
    print("-" * 78)
    container_ids = set()
    for s in sections:
        if str(s.get("tipe_bagian", "")) == "bab":
            container_ids.add(to_int(s.get("id")))
    found = []
    for cid_sec in sorted(container_ids):
        cnt = len([b for b in blocks if to_int(b.get("section_id")) == cid_sec])
        if cnt > 0:
            found.append((cid_sec, cnt))
    if found:
        for cid_sec, cnt in found:
            print("  container section %d -> %d blok dengan section_id=ID" % (cid_sec, cnt))
    else:
        print("  (tidak ada)")

    print("\n" + "=" * 78)
    print("SELESAI — tidak ada perubahan data.")
    print("=" * 78)


if __name__ == "__main__":
    main()
