#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STAGE 0 — AUDIT DATA READ-ONLY
=================================================
Membaca dump SQL (manuputr_perpus_kitab.sql) ke memori dan menjalankan
pemeriksaan read-only. TIDAK menyentuh database, TIDAK menulis apa pun
selain output ke STDOUT.

Pemeriksaan:
  1. Duplikasi Subbab dengan `urutan` sama dalam Bab yang sama.
  2. Duplikasi Content Block berdasarkan (chapter_id, section_id, sort_order).
  3. Bab/Subbab yang punya section_texts tetapi belum punya Content Block.
  4. Jumlah data terdampak + ID + referensi.
"""

import os
import re
import sys

DUMP = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "manuputr_perpus_kitab.sql")


def parse_insert_rows(sql, table):
    """Ekstrak semua baris tuple dari INSERT INTO `table` (...) VALUES (...),(...);"""
    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(",")]
        tuples = parse_value_tuples(sql, m.end())
        for tup in tuples:
            if len(tup) != len(cols):
                continue
            rows.append(dict(zip(cols, tup)))
    return rows


def parse_value_tuples(s, pos):
    """Parse rangkaian tuple "(...),(...);" mulai dari offset."""
    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 = False
        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
            # di luar string
            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()
    if t.upper() == "NULL":
        return None
    return t


def to_int(v):
    try:
        return int(v)
    except (TypeError, ValueError):
        return None


def main():
    if not os.path.isfile(DUMP):
        print("Dump tidak ditemukan: %s" % DUMP, file=sys.stderr)
        return 1
    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_name = {to_int(c.get("id")): (c.get("judul_indonesia") or c.get("judul_arab") or "?") for c in chapters}
    section_info = {}
    for s in sections:
        section_info[to_int(s.get("id"))] = {
            "chapter_id": to_int(s.get("chapter_id")),
            "urutan": to_int(s.get("urutan")),
            "tipe_bagian": s.get("tipe_bagian"),
            "judul": s.get("judul_indonesia") or s.get("judul_arab") or "?",
        }

    print("=" * 62)
    print(" STAGE 0 — AUDIT DATA READ-ONLY (sumber: dump SQL)")
    print("=" * 62)
    print("books          : %d" % len(books))
    print("chapters       : %d" % len(chapters))
    print("sections       : %d" % len(sections))
    print("section_texts  : %d" % len(section_texts))
    print("content_blocks : %d" % len(blocks))
    print("-" * 62)
    print()

    # ---------------------------------------------------------------
    # 1) Duplikasi Subbab: urutan sama dalam chapter_id sama
    # ---------------------------------------------------------------
    print("### 1) DUPLIKASI SUBBAB (chapter_id + urutan sama)")
    by_chapter_urutan = {}
    for s in sections:
        cid = to_int(s.get("chapter_id"))
        uru = to_int(s.get("urutan"))
        by_chapter_urutan.setdefault(cid, {}).setdefault(uru, []).append(s)

    dup_subbab = []
    for cid, urutans in by_chapter_urutan.items():
        for uru, lst in urutans.items():
            if len(lst) > 1:
                dup_subbab.append((cid, uru, lst))

    if not dup_subbab:
        print("Jumlah temuan: 0 (TIDAK ADA duplikasi subbab berdasarkan urutan).")
    else:
        print("Jumlah grup duplikat: %d" % len(dup_subbab))
        for cid, uru, lst in dup_subbab:
            print("  - Chapter #%s (%s) | urutan=%s" % (cid, chapter_name.get(cid, "?"), uru))
            for r in lst:
                print("      section_id=%s tipe_bagian=%s judul=\"%s\""
                      % (r.get("id"), r.get("tipe_bagian") or "-", r.get("judul_indonesia") or r.get("judul_arab") or "?"))
    print()

    # ---------------------------------------------------------------
    # 2) Duplikasi Content Block: (chapter_id, section_id, sort_order)
    # ---------------------------------------------------------------
    print("### 2) DUPLIKASI CONTENT BLOCK (chapter_id + section_id + sort_order)")
    by_key = {}
    for b in blocks:
        cid = to_int(b.get("chapter_id"))
        sid = b.get("section_id")
        sid_key = "NULL" if sid is None else str(to_int(sid))
        so = to_int(b.get("sort_order"))
        by_key.setdefault((cid, sid_key, so), []).append(b)

    dup_blocks = [(k, v) for k, v in by_key.items() if len(v) > 1]
    if not dup_blocks:
        print("Jumlah temuan: 0 (TIDAK ADA duplikasi content block).")
    else:
        print("Jumlah grup duplikat: %d" % len(dup_blocks))
        total_rows = 0
        for (cid, sid_key, so), lst in dup_blocks:
            total_rows += len(lst)
            print("  - Chapter #%s (%s) | section_id=%s | sort_order=%s | jumlah baris=%d"
                  % (cid, chapter_name.get(cid, "?"), sid_key, so, len(lst)))
            for r in lst:
                preview = (r.get("text_arab") or "")[:40].replace("\n", " ")
                print("      block_id=%s type=%s preview=\"%s...\"" % (r.get("id"), r.get("block_type"), preview))
        print("  Total baris terlibat: %d" % total_rows)
    print()

    # ---------------------------------------------------------------
    # 3) Unit punya section_texts tetapi belum punya content_blocks
    # ---------------------------------------------------------------
    print("### 3) UNIT PUNYA section_texts TAPI BELUM PUNYA content_blocks")

    text_per_section = {}
    for t in section_texts:
        sid = to_int(t.get("section_id"))
        text_per_section[sid] = text_per_section.get(sid, 0) + 1

    block_per_section = {}
    for b in blocks:
        if b.get("section_id") is not None:
            sid = to_int(b.get("section_id"))
            block_per_section[sid] = block_per_section.get(sid, 0) + 1

    missing_subbab = {sid: cnt for sid, cnt in text_per_section.items() if sid not in block_per_section}

    # per BAB
    chapter_has_text = {}
    for t in section_texts:
        sid = to_int(t.get("section_id"))
        info = section_info.get(sid)
        if info and info["chapter_id"] is not None:
            cid = info["chapter_id"]
            chapter_has_text[cid] = chapter_has_text.get(cid, 0) + 1

    chapter_has_block = {}
    for b in blocks:
        cid = to_int(b.get("chapter_id"))
        chapter_has_block[cid] = chapter_has_block.get(cid, 0) + 1

    missing_chapter = {cid: cnt for cid, cnt in chapter_has_text.items() if cid not in chapter_has_block}

    print("3a. SUBBAB tanpa content_blocks:")
    if not missing_subbab:
        print("    Jumlah temuan: 0 (semua SUBBAB yang punya teks sudah punya blok).")
    else:
        print("    Jumlah SUBBAB terdampak: %d" % len(missing_subbab))
        for sid, cnt in sorted(missing_subbab.items(), key=lambda x: (x[0] is None, x[0])):
            info = section_info.get(sid, {})
            print("      section_id=%s (chapter #%s, \"%s\", tipe=%s) — %d baris teks, 0 blok"
                  % (sid, info.get("chapter_id"), info.get("judul", "?"), info.get("tipe_bagian") or "-", cnt))

    print()
    print("3b. BAB tanpa content_blocks sama sekali (padahal punya teks):")
    if not missing_chapter:
        print("    Jumlah temuan: 0 (semua BAB yang punya teks sudah punya blok).")
    else:
        print("    Jumlah BAB terdampak: %d" % len(missing_chapter))
        for cid, cnt in sorted(missing_chapter.items()):
            print("      chapter_id=%s (%s) — %d baris teks, 0 blok"
                  % (cid, chapter_name.get(cid, "?"), cnt))
    print()

    # ---------------------------------------------------------------
    # 4) Ringkasan
    # ---------------------------------------------------------------
    print("### 4) RINGKASAN")
    print("1. Duplikasi subbab (urutan sama)      : %d grup" % len(dup_subbab))
    print("2. Duplikasi content block             : %d grup" % len(dup_blocks))
    print("3. SUBBAB punya teks tanpa blok        : %d unit" % len(missing_subbab))
    print("   BAB punya teks tanpa blok           : %d unit" % len(missing_chapter))
    print("=" * 62)
    return 0


if __name__ == "__main__":
    sys.exit(main())
