#!/usr/bin/env python3
"""Build the translation inventory (notes/translation-review/inventory.json).

Read-only over the repository; writes only inside notes/translation-review/.
Run from the repository root:  python notes/translation-review/tools/inventory.py
Classifies every text file at the pinned source revision as hand-maintained
prose, generated view, canonical-data prose or machine data, counts Malayalam
characters and words, and joins the staging status from manifest.json.
"""
import json, re, subprocess, sys
from pathlib import Path

ROOT = Path.cwd()
STAGE = ROOT / "notes/translation-review"
MARKER = "GENERATED by scripts/build.py"
ML = re.compile(r"[\u0D00-\u0D7F]")
rev = subprocess.check_output(["git", "rev-parse", "origin/main"], text=True).strip()

def show(path):
    return subprocess.check_output(["git", "show", f"{rev}:{path}"], text=True)

files = subprocess.check_output(["git", "ls-tree", "-r", "--name-only", rev], text=True).split()
manifest = json.loads((STAGE / "manifest.json").read_text(encoding="utf-8")) if (STAGE / "manifest.json").exists() else {"entries": []}
staged = {}
for e in manifest["entries"]:
    staged.setdefault(e["source_path"] + ("#" + e["source_id"] if e.get("source_id") else ""), e)

# Batch plan by path (chosen after inventory; see INVENTORY.md).
B1 = {"README.md", "CONTRIBUTING.md", "docs/EVIDENCE_POLICY.md", "docs/RIGHTS_AND_ETHICS.md",
      "docs/CHRONOLOGY.md", "docs/DATA_MODEL.md", "notes/README.md", "templates/research-note.md",
      ".github/ISSUE_TEMPLATE/correction.md", ".github/ISSUE_TEMPLATE/source.md",
      ".github/PULL_REQUEST_TEMPLATE.md", "docs/work-packages/translation.md"}
B2_DATA = {"data/periods.json", "data/records.json", "data/sources.json"}

def plan(path):
    if path in B1: return 1
    if path in B2_DATA or path.startswith(("periods/", "records/", "sources/")): return 2
    return 3

out = {"source_revision": rev, "hand_maintained": [], "generated": [], "data_prose": [], "excluded": []}
for f in files:
    if f.startswith("notes/translation-review/"):
        continue
    if f.startswith(("LICENSES/",)) or f in {"MANIFEST.sha256", "LICENSE.md"} and False:
        pass
    try:
        text = show(f)
    except Exception:
        continue
    words = len(re.findall(r"\w+", re.sub(r"`[^`]*`|\(\S+?\)", "", text)))
    item = {"path": f, "bytes": len(text.encode()), "words": words,
            "malayalam_chars": len(ML.findall(text)), "em_dashes": text.count("\u2014"), "batch": plan(f)}
    if f.endswith(".md"):
        if MARKER in text:
            out["generated"].append(item)
        else:
            out["hand_maintained"].append(item)
    elif f in {"coverage/year-status.csv", "coverage/stats.json"}:
        item["note"] = "generated machine data; column/key names stay English; only labels may need display translation"
        out["generated"].append(item)
    elif f.startswith("data/") or f == "geography/scope.json" or f.startswith("templates/"):
        out["data_prose"].append(item)
    else:
        item["reason"] = "code, schema, license text, checksum or machine metadata; not translated"
        out["excluded"].append(item)

# Canonical-data prose fields (translatable human-readable strings).
FIELDS = {
    "data/periods.json": ["title", "display_window", "central_question", "established_in_this_pass", "limitations", "research_tasks"],
    "data/records.json": ["title", "claim", "caveat", "date.original_expression", "date.calendar", "date.datum", "authoring", "rights"],
    "data/sources.json": ["title(original: retain; explanatory gloss only)", "inspection_note", "rights"],
    "data/audit.json": ["earlier_claim", "corrected_treatment"],
    "data/corpora.json": ["name", "next_task"],
    "data/prior_chapter_crosswalk.json": ["title", "assessment"],
}
def get(obj, dotted):
    for k in dotted.split("(")[0].split("."):
        obj = obj.get(k) if isinstance(obj, dict) else None
    return obj
fields = []
for path, names in FIELDS.items():
    rows = json.loads(show(path))
    for name in names:
        n_items = n_words = 0
        for row in rows:
            v = get(row, name)
            for s in (v if isinstance(v, list) else [v]):
                if isinstance(s, str) and s.strip():
                    n_items += 1; n_words += len(s.split())
        fields.append({"path": path, "field": name, "records": len(rows), "strings": n_items, "words": n_words, "batch": plan(path)})
staged_keys = set()
for f in STAGE.rglob("*.ml.json"):
    for e in json.loads(f.read_text(encoding="utf-8"))["entries"]:
        staged_keys.add(e["key"])
def staged_count(path, name):
    base = name.split("(")[0]
    return sum(1 for k in staged_keys if k.startswith(path + "#") and re.sub(r"\[\d+\]$", "", k.split("#")[1].split(".", 1)[1]) == base)
for fl in fields:
    fl["staged"] = staged_count(fl["path"], fl["field"])
out["data_prose_fields"] = fields
scope = json.loads(show("geography/scope.json"))
out["data_prose_fields"].append({"path": "geography/scope.json", "field": "inclusion_rule, offshore_rule, exclusions_and_context", "records": 1,
    "strings": 2 + len(scope["exclusions_and_context"]), "staged": sum(1 for k in staged_keys if k.startswith("geography/scope.json#")), "words": sum(len(x.split()) for x in [scope["inclusion_rule"], scope["offshore_rule"], *scope["exclusions_and_context"]]), "batch": 3})

# Staging status join.
for group in ("hand_maintained", "generated", "data_prose"):
    for item in out[group]:
        hits = [e for e in manifest["entries"] if e["source_path"] == item["path"]]
        item["staging"] = sorted({e["status"] for e in hits}) or ["untranslated"]
(STAGE / "inventory.json").write_text(json.dumps(out, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
gen_dirs = {}
for g in out["generated"]:
    d = g["path"].split("/")[0] + ("/" + g["path"].split("/")[1] if g["path"].startswith("years/") else "")
    gen_dirs.setdefault(d, [0, 0]); gen_dirs[d][0] += 1; gen_dirs[d][1] += g["words"]
print(json.dumps({"hand_maintained": len(out["hand_maintained"]), "generated": len(out["generated"]),
                  "data_prose_files": len(out["data_prose"]), "excluded": len(out["excluded"]), "generated_by_dir": gen_dirs}, indent=1))

# ---- Render INVENTORY.md -------------------------------------------------
BATCH_NAMES = {1: "1 (PR #3)", 2: "2", 3: "3"}
def st(i): return ", ".join(i["staging"])
L = []
L.append("# പരിഭാഷാപട്ടിക / Translation inventory\n")
L.append(f"നിർമ്മിച്ചത് `tools/inventory.py` ഉപയോഗിച്ച്, source revision `{rev}`. ഈ ഫയൽ കൈകൊണ്ട് തിരുത്തരുത്; script വീണ്ടും പ്രവർത്തിപ്പിക്കുക.\n")
L.append(f"Generated by `tools/inventory.py` at source revision `{rev}`. Rerun the script instead of editing. Word counts are approximate (inline code and link targets removed). `ML chars` counts Malayalam code points already present.\n")
L.append("## ചുരുക്കം / Summary\n")
L.append("| വിഭാഗം / Category | ഫയലുകൾ / Files | ബാച്ച് / Batch |\n|---|---:|---|")
L.append(f"| Hand-maintained Markdown prose | {len(out['hand_maintained'])} | 1 and 3 |")
L.append(f"| Generated views (Markdown, CSV, JSON stats) | {len(out['generated'])} | 2 (records/sources/periods) and 3 (years, audit, coverage, labels) |")
L.append(f"| Canonical data and config files with prose | {len(out['data_prose'])} | 2 and 3 |")
L.append(f"| Excluded (code, schema JSON, license text, checksums) | {len(out['excluded'])} | none |\n")
L.append("## 1. Hand-maintained prose\n")
L.append("| Path | Words | ML chars | Em dashes | Batch | Staging status |\n|---|---:|---:|---:|---|---|")
for i in sorted(out["hand_maintained"], key=lambda x: (x["batch"], x["path"])):
    L.append(f"| `{i['path']}` | {i['words']} | {i['malayalam_chars']} | {i['em_dashes']} | {BATCH_NAMES[i['batch']]} | {st(i)} |")
L.append("| `docs/work-packages/translation.md` (branch only, `1e8d0ef`) | n/a | bilingual | 0 | 1 (PR #3) | already_bilingual_reviewed_by_model |")
L.append("\n## 2. Generated text\n")
L.append("Generated pages must not be edited directly. Their prose comes from canonical data (section 3) plus fixed generator strings in `scripts/build.py` (section 4). Translation is staged against those inputs, not against the pages.\n")
L.append("| Generated group | Files | Words | Em dashes | Prose comes from | Batch | Staging status |\n|---|---:|---:|---:|---|---|---|")
groups = {}
for g in out["generated"]:
    p = g["path"]
    key = "years/BCE" if p.startswith("years/BCE") else "years/CE" if p.startswith("years/CE") else p.split("/")[0] if "/" in p else p
    if p == "years/README.md": key = "years/README.md"
    groups.setdefault(key, []).append(g)
SRC = {"periods": "data/periods.json + generator labels", "records": "data/records.json + generator labels",
       "sources": "data/sources.json + generator labels", "audit": "data/audit.json, data/prior_chapter_crosswalk.json + labels",
       "coverage": "data counts + generator labels", "years/BCE": "generator labels + record/period titles",
       "years/CE": "generator labels + record/period titles", "years/README.md": "generator labels"}
for k in sorted(groups):
    v = groups[k]
    b = 2 if k in ("periods", "records", "sources") else 3
    sts = sorted({s for x in v for s in x["staging"]})
    if k in ("periods", "records", "sources") and any(kk.startswith(f"data/{k}.json#") for kk in staged_keys):
        sts = ["data prose staged (batch 2)", "generator labels staged (batch 3), needs generator support"]
    elif k == "audit": sts = ["data prose staged (batch 3)", "generator labels staged (batch 3), needs generator support"]
    elif any(kk.startswith("scripts/build.py#") for kk in staged_keys): sts = ["generator labels staged (batch 3), needs generator support; record/period titles staged (batch 2)"]
    L.append(f"| `{k}` | {len(v)} | {sum(x['words'] for x in v)} | {sum(x['em_dashes'] for x in v)} | {SRC.get(k, '')} | {b} | {', '.join(sts)} |")
L.append("\n## 3. Prose supplied by canonical data\n")
L.append("Keys, IDs, enums, URLs, DOIs, locators and structured dates stay untranslated. Prose date.calendar descriptions are counted as translatable text. Source titles stay in their original form.\n")
L.append("| File | Field | Records | Strings | Staged ML | Words | Batch |\n|---|---|---:|---:|---:|---:|---|")
for i in out["data_prose_fields"]:
    L.append(f"| `{i['path']}` | `{i['field']}` | {i['records']} | {i['strings']} | {i.get('staged', 0)} | {i['words']} | {i['batch']} |")
L.append("| `templates/record.json` | example placeholder strings | 1 | n/a | 0 | 106 (file) | 3 |")
tot = sum(i["strings"] for i in out["data_prose_fields"]); stg = sum(i.get("staged", 0) for i in out["data_prose_fields"])
L.append(f"\nData prose strings staged: **{stg} of {tot}** (source titles counted as strings but intentionally retained, not translated).")
L.append("\n## 4. Generator-supplied labels\n")
gen_src = show("scripts/build.py")
labels = sorted(set(re.findall(r"'(#+ [^'\\]{3,}|\*\*[A-Z][^'*]{3,}\*\*[^'\\]*)", gen_src)))
L.append(f"`scripts/build.py` contains fixed reader-facing headings and sentences (about {len(labels)} heading/bold-label literals found by pattern, plus register introductions and coverage table labels). Batch 3 stages Malayalam for them in [batch-3/generator-labels.ml.json](batch-3/generator-labels.ml.json) ("+str(sum(1 for k in staged_keys if k.startswith('scripts/build.py#')))+" keys including verdict display labels); rendering requires generator support (see [INTEGRATION_NOTES.md](INTEGRATION_NOTES.md)).\n")
L.append("## 5. Excluded from translation\n")
for i in out["excluded"]:
    L.append(f"- `{i['path']}`: {i['reason']}")
L.append("\nThe separate English-only landing page is outside this repository and outside scope.")
(STAGE / "INVENTORY.md").write_text("\n".join(L) + "\n", encoding="utf-8")
