#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
STAGE 0 — COVERAGE CHECK READ-ONLY
=================================================
Memeriksa apakah teks pada unit "tanpa blok" sudah tercakup oleh blok
BAB-direct (section_id NULL) pada chapter yang sama. Ini mencegah
false-positive: unit bisa saja belum punya blok sendiri, tetapi teksnya
sudah ter-parse sebagai blok BAB-direct.

Read-only, hanya membaca dump.
"""

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")


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 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")),
            "tipe": s.get("tipe_bagian"),
            "judul": s.get("judul_indonesia") or s.get("judul_arab") or "?",
        }

    texts_by_section = {}
    for t in section_texts:
        texts_by_section.setdefault(to_int(t.get("section_id")), []).append(t)

    blocks_by_section = {}
    bab_direct_text = {}
    for b in blocks:
        cid = to_int(b.get("chapter_id"))
        if b.get("section_id") is None:
            bab_direct_text.setdefault(cid, []).append(norm(b.get("text_arab")))
        else:
            sid = to_int(b.get("section_id"))
            blocks_by_section[sid] = blocks_by_section.get(sid, 0) + 1

    print("=" * 78)
    print(" STAGE 0 — COVERAGE CHECK (apakah teks unit tanpa-blok tercakup BAB-direct?)")
    print("=" * 78)

    missing = [sid for sid in texts_by_section if sid not in blocks_by_section]
    covered = 0
    not_covered = 0

    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, [])
        direct = " ".join(bab_direct_text.get(cid, []))
        direct_words = set(direct.split())

        print("\n  section_id=%s | chapter #%s (%s) | tipe=%s | \"%s\""
              % (sid, cid, chapter_name.get(cid, "?"), info.get("tipe") or "-", info.get("judul", "?")))

        for r in rows:
            txt = norm(r.get("teks_arab"))
            words = txt.split()
            if not words:
                continue
            if not direct_words:
                status = "TIDAK ADA blok BAB-direct di chapter ini"
                not_covered += 1
            else:
                hit = sum(1 for w in words if w in direct_words)
                pct = 100.0 * hit / len(words)
                if pct >= 80.0:
                    status = "TERCAKUP %.1f%% oleh blok BAB-direct" % pct
                    covered += 1
                else:
                    status = "BELUM tercakup (hanya %.1f%% kata cocok)" % pct
                    not_covered += 1
            print("      text_id=%s (%d kata): %s" % (r.get("id"), len(words), status))

    print("\n" + "-" * 78)
    print("RINGKASAN COVERAGE:")
    print("  Unit tanpa blok sendiri yang teksnya SUDAH tercakup BAB-direct : %d" % covered)
    print("  Unit tanpa blok sendiri yang teksnya BELUM tercakup           : %d" % not_covered)
    print("=" * 78)
    return 0


if __name__ == "__main__":
    sys.exit(main())
