#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Build offline Markdown views from canonical JSON. No web requests or dependencies.

Run from any directory: python /path/to/repo/scripts/build.py
Generated files are replaceable views. Hand-authored additions belong in notes/.
The preflight refuses to overwrite files without this generator's marker.

Optional Malayalam catalogues in data/i18n/ml/ add Malayalam first and English
second wherever a current translation exists (see docs/BILINGUAL_DATA.md).
Without catalogues the output is English only, exactly as before.
"""
from __future__ import annotations
import argparse
import csv
import io
import json
import os
import re
import sys
from collections import Counter
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(Path(__file__).resolve().parent))
import bilingual  # noqa: E402

MARKER = '<!-- GENERATED by scripts/build.py; edit canonical data, not this view. -->'
GENERATED_DIRS = ('sources', 'records', 'periods', 'years', 'audit', 'coverage')
ROLES = {
    'exact_date': 'Day explicitly dated in the inspected source',
    'year_attested': 'Year attested; day not normalized',
    'conventional_date': 'Conventional or reconstructed year; review pending',
    'proposed_date': 'Proposed date, not an established exact-year event',
    'research_history': 'Research, publication, registration or digital-access history',
}
# Structural grouping of the free-text inspection labels used on source cards.
# Metadata, abstract or description, passage and full-text inspection are
# different statuses; a new label must be placed here deliberately (validate.py
# rejects unmapped labels). This grouping is an editorial aid, not a quality score.
INSPECTION_DEPTH = {
    'access_failed': 'not_accessed',
    'search_index_only': 'metadata', 'metadata_only': 'metadata',
    'abstract_only': 'abstract_or_description', 'abstract_and_catalogue': 'abstract_or_description',
    'abstract_and_metadata': 'abstract_or_description', 'metadata_and_abstract': 'abstract_or_description',
    'institutional_description': 'abstract_or_description', 'institutional_page': 'abstract_or_description',
    'full_landing_page': 'abstract_or_description', 'landing_and_volume_index': 'abstract_or_description',
    'full_catalogue_page': 'abstract_or_description',
    'relevant_passage': 'passage', 'relevant_passages': 'passage', 'selected_pages_and_images': 'passage',
    'selected_sections_and_images': 'passage', 'proposal_and_final_outcomes': 'passage',
    'full_page': 'full_text',
    # Evidence-review vocabulary (notes/evidence-review/claim-reviews.json, PR #4).
    'abstract_and_preview': 'abstract_or_description',
    'relevant_passages_translation': 'passage', 'relevant_passages_ocr_text': 'passage',
    'relevant_passages_secondary_copy': 'passage',
    'full_text': 'full_text',
}
DEPTH_ORDER = ('not_accessed', 'metadata', 'abstract_or_description', 'passage', 'full_text')

# Reader-facing generator text, keyed for translation catalogues as
# scripts/build.py#<key>. kind decides how Malayalam and English are joined:
# heading, bold, bracket, inline, block, table_row. {name} marks a template slot.
LABELS = {f'roles.{k}': ('inline', v) for k, v in ROLES.items()}
LABELS.update({
    'source_refs.none': ('inline', 'No historical source claim; research task only.'),
    'source.creator': ('bold', '**Creator:**'),
    'source.type': ('bold', '**Type:**'),
    'source.inspection': ('bold', '**Inspection:**'),
    'source.accessed': ('bold', '**Accessed:**'),
    'source.link': ('bracket', '[Source / catalogue]'),
    'source.pubyear': ('block', '**Registered publication year:** {year}; consult the note for version distinctions.'),
    'source.h_inspected': ('heading', '## What was inspected'),
    'source.h_rights': ('heading', '## Rights and copies'),
    'source.no_bundle': ('block', 'No third-party full text or image is bundled. A null checksum means no local source file was preserved; it is not an integrity check.'),
    'source.h_alt': ('heading', '## Alternate discovery or metadata routes'),
    'source.alt_n': ('inline', 'Alternative {n}'),
    'source.h_linked': ('heading', '## Linked evidence records'),
    'source.no_linked': ('block', 'No seed evidence record uses this source yet; it may be a methodology source or collection lead.'),
    'sources_readme.title': ('heading', '# Source register'),
    'sources_readme.intro': ('block', 'Inspection depth is not a quality score. A primary document can be biased; a catalogue can only establish what was actually inspected. All independent human review is pending.'),
    'record.evidence_type': ('bold', '**Evidence type:**'),
    'record.geo_relation': ('bold', '**Geographic relation:**'),
    'record.places': ('bold', '**Places:**'),
    'record.global': ('inline', 'Global context, not a local site'),
    'record.h_date': ('heading', '## Date as represented'),
    'record.other_dates': ('block', 'Other, separately typed dates:'),
    'record.h_limitations': ('heading', '## Limitations'),
    'record.h_evidence': ('heading', '## Evidence and locators'),
    'record.inspection': ('inline', 'Inspection:'),
    'record.h_nav': ('heading', '## Navigation'),
    'record.h_review': ('heading', '## Review and authorship'),
    'record.human_review': ('bold', '**Independent human review:**'),
    'record.created_updated': ('bold', '**Created / updated:**'),
    'records_readme.title': ('heading', '# Evidence records'),
    'records_readme.intro': ('block', 'These are attributed, limited seed records. A research publication is not the historical event it discusses.'),
    'period.window': ('bold', '**Window:**'),
    'period.question': ('bold', '**Question:**'),
    'period.h_evidence': ('heading', '## Evidence presently available in this seed'),
    'period.source_routes': ('inline', 'Source routes:'),
    'period.h_not': ('heading', '## What this does not establish'),
    'period.h_tasks': ('heading', '## Research tasks'),
    'period.h_records': ('heading', '## Canonical seed records'),
    'period.no_records': ('block', 'No canonical evidence record has been entered for this dossier yet.'),
    'period.h_coverage': ('heading', '## Coverage note'),
    'period.coverage': ('block', 'This is an open research dossier, not an exhaustive era narrative. Its window is an editorial retrieval aid and can overlap other dossiers. Primary evidence, source dates and interpretative disputes remain explicit. Human specialist review is pending.'),
    'periods_readme.title': ('heading', '# Era and period dossiers'),
    'periods_readme.intro': ('block', 'The first twelve dossiers organize deep time and prehistory. Seven overlapping editorial windows connect the documentary periods to annual navigation. These are not a claim that all districts followed the same sequence.'),
    'year.index': ('inline', '[Year index](../README.md)'),
    'year.coverage': ('bold', '**Coverage:**'),
    'year.coverage_seed': ('inline', 'A small number of source-linked seeds; not a completed year history.'),
    'year.coverage_none': ('inline', 'No year-specific seed has been entered. This year has not been exhaustively researched.'),
    'year.partial': ('block', '**Partial year:** this release stops at {as_of}. No later event is implied.'),
    'year.h_wider': ('heading', '## Wider-period evidence: not an event assigned to this year'),
    'year.period_index': ('inline', 'Consult the [period index](../../periods/README.md).'),
    'year.h_interp': ('heading', '## Interpretation'),
    'year.interp1': ('block', 'An empty section is not proof that nothing happened or that no records survive. Century-dated and undated material stays in its period dossier; publication and discovery dates are separate from the events studied.'),
    'year.interp2': ('block', 'Add a canonical record in `data/records.json`, cite a source with a locator, and rebuild. Hand-authored research notes belong in `notes/`, not this generated page.'),
    'era_index.title': ('heading', '# {era} annual index'),
    'era_index.intro': ('block', 'Generated navigation, not a measure of historical coverage.'),
    'era_index.range': ('heading', '## {start} through {end}'),
    'years_readme.title': ('heading', '# Annual navigation'),
    'years_readme.p1': ('block', 'This release creates **{n} annual Markdown files**, from {start} through {end}, with no year zero. The starting boundary is editorial, not proof that writing began in 300 BCE.'),
    'years_readme.nav': ('inline', '[Browse BCE](BCE/README.md) · [Browse CE](CE/README.md) · [Era and period dossiers](../periods/README.md)'),
    'years_readme.p2': ('block', 'Most annual pages are unresearched navigation placeholders. A period link is not a year-specific event. See [coverage](../coverage/README.md).'),
    'audit.title': ('heading', '# Audit of the earlier conversation'),
    'audit.intro': ('block', 'This register separates factual claims, misleading implications, omissions, and proposed research topics. It is not a declaration that every topic is now fully verified. Repeated claims are consolidated; the 46-chapter crosswalk below preserves the full outline. "Pending" means the necessary primary evidence has not been inspected.'),
    'audit.earlier': ('bold', '**Earlier claim or implication:**'),
    'audit.treatment': ('bold', '**Treatment:**'),
    'audit.route': ('bold', '**Evidence route:**'),
    'audit.h_crosswalk': ('heading', '## Crosswalk of every chapter in the earlier 46-chapter proposal'),
    'audit.table_head': ('table_row', '| Chapter | Proposed subject | Dossier(s) | Audit status |'),
    'coverage.title': ('heading', '# Coverage: version {version}'),
    'coverage.asof': ('block', 'As of {as_of}. These are repository counts, not estimates of the total historical record.'),
    'coverage.th': ('table_row', '| Measure | This release |'),
    'coverage.r1': ('inline', 'Annual Markdown files'),
    'coverage.r2': ('inline', 'Annual pages with at least one year-specific seed link'),
    'coverage.r3': ('inline', 'Annual pages without a year-specific seed'),
    'coverage.r4': ('inline', 'Canonical evidence records'),
    'coverage.r5': ('inline', 'Source cards, including catalogues and leads'),
    'coverage.r6': ('inline', 'Deep-time / prehistory dossiers'),
    'coverage.r7': ('inline', 'Documentary-period dossiers'),
    'coverage.r8': ('inline', 'Independent human-reviewed records'),
    'coverage.r9': ('inline', 'Completed collection inventories'),
    'coverage.r10': ('inline', 'Third-party full texts or images bundled'),
    'coverage.r11': ('inline', 'Verified current boundary polygons'),
    'coverage.p1': ('block', 'The seed entries include research and publication milestones. They must not be reported as that many unique past events in the territory. Sources inspected only as abstracts or catalogues are clearly labelled. Empty years are unresearched, not historically empty.'),
    'coverage.p2': ('block', 'No percentage for coverage of the entire internet is calculated. No source corpus has been completely inventoried. [Collection plan](../docs/CORPUS_PLAN.md) defines what an auditable completeness claim would require.'),
    'coverage.links': ('inline', '[Machine-readable statistics](stats.json) · [Year-by-year status](year-status.csv)'),
    # Added with the separate counts; their Malayalam ships in data/i18n/ml/labels.json.
    'coverage.h_separate': ('heading', '## Separate measures'),
    'coverage.year_links': ('inline', 'Year links from evidence records'),
    'coverage.records_with_links': ('inline', 'Evidence records with at least one year link'),
    'coverage.past_event_pages': ('inline', 'Annual pages that link a past-event date'),
    'coverage.research_only_pages': ('inline', 'Annual pages that link only research, publication or access history'),
    'coverage.sources_cited': ('inline', 'Source cards cited by at least one evidence record'),
    'coverage.sources_passage': ('inline', 'Source cards inspected at passage or full-text depth'),
    'coverage.sources_shallow': ('inline', 'Source cards seen only as metadata, or not accessed'),
    'coverage.sources_reviewed': ('inline', 'Source cards with independent human review'),
    'coverage.ml_fields': ('inline', 'Canonical-data text fields with a current Malayalam translation'),
    'coverage.ml_labels': ('inline', 'Generator labels with a current Malayalam translation'),
    'coverage.ml_reviewed': ('inline', 'Malayalam translations with a recorded human language review'),
    'coverage.of': ('inline', '{n} of {total}'),
    'coverage.p_separate': ('block', 'Year links, records, source cards and inspected sources are counted separately. Translation coverage, source inspection and scholarly review are different measures: a Malayalam translation does not mean a claim was checked, and an inspected source card does not mean the full text was read.'),
})


def label_texts(data: dict | None = None) -> dict:
    """All label keys for this data: the static labels plus one per audit verdict."""
    out = dict(LABELS)
    for a in (data or {}).get('audit') or []:
        v = a.get('verdict') if isinstance(a, dict) else None
        if isinstance(v, str):
            out[f'verdict.{v}'] = ('inline', v.replace('_', ' '))
    return out


def load(name: str):
    return json.loads((ROOT/name).read_text(encoding='utf-8'))


def load_data() -> dict:
    return {'project': load('project.json'), 'sources': load('data/sources.json'), 'periods': load('data/periods.json'),
            'records': load('data/records.json'), 'audit': load('data/audit.json'), 'corpora': load('data/corpora.json'),
            'crosswalk': load('data/prior_chapter_crosswalk.json'), 'scope': load('geography/scope.json')}

def years(start: int, end: int) -> list[int]:
    if start == 0 or end == 0 or start > end:
        raise ValueError('Use ordered, nonzero historical years.')
    return [n for n in range(start, end+1) if n != 0]

def label(year: int) -> str:
    if year == 0:
        raise ValueError('No year zero in this repository.')
    return f'{abs(year)} {"BCE" if year < 0 else "CE"}'

def year_path(year: int) -> Path:
    if year == 0:
        raise ValueError('No year zero in this repository.')
    return Path('years')/('BCE' if year < 0 else 'CE')/f'{abs(year):04d}.md'

def rel(target: str | Path, origin: str | Path) -> str:
    return os.path.relpath(ROOT/target, (ROOT/origin).parent).replace(os.sep,'/')

def frontmatter(obj: dict) -> str:
    # JSON values are valid YAML scalars/flow collections; no YAML dependency.
    return '---\n' + '\n'.join(f'{k}: {json.dumps(v, ensure_ascii=False)}' for k,v in obj.items()) + '\n---\n'


_SINGLE_LINK = re.compile(r'\[([^\]]*)\]\(([^)]*)\)')


def combine(kind: str, ml: str, en: str) -> str:
    """Join Malayalam (first) and English (second) for one unit of text."""
    if kind == 'heading':
        h = re.match(r'#+ ', en).group(0)
        return f'{h}{ml[len(h):]} / {en[len(h):]}'
    if kind == 'bold':
        return f'**{ml[2:-2]} / {en[2:-2]}**'
    if kind == 'bracket':
        return f'[{ml[1:-1]} / {en[1:-1]}]'
    if kind == 'table_row':
        m = ml.strip().strip('|').split('|'); e = en.strip().strip('|').split('|')
        return '| ' + ' | '.join(f'{a.strip()} / {b.strip()}' for a, b in zip(m, e)) + ' |'
    if kind == 'block':
        return f'{ml}\n\n{en}'
    if kind == 'line':
        return f'{ml}  \n{en}'
    if kind == 'list':
        return f'{ml}  \n  {en}'
    ma, ea = _SINGLE_LINK.fullmatch(ml), _SINGLE_LINK.fullmatch(en)
    if ma and ea and ma.group(2) == ea.group(2):
        return f'[{ma.group(1)} / {ea.group(1)}]({ea.group(2)})'
    return f'{ml} / {en}'


NOTICE_METHOD = {True: ('ഈ പേജിലെ മലയാളം AI സഹായത്തോടെ തയ്യാറാക്കിയതാണ്', 'The Malayalam on this page is AI-assisted'),
                 False: ('ഈ പേജിലെ മലയാളം മനുഷ്യർ പരിഭാഷപ്പെടുത്തിയതാണ്', 'The Malayalam on this page was translated by people')}
NOTICE_REVIEW = {False: ('മനുഷ്യ ഭാഷാപരിശോധന ബാക്കിയാണ്', 'human language review is pending'),
                 True: ('ഓരോ ഭാഗത്തിനും മനുഷ്യ ഭാഷാപരിശോധന രേഖപ്പെടുത്തിയിട്ടുണ്ട്', 'human language review is recorded for each passage')}
GLOSS_LABEL = '**വിശദീകരണ പരിഭാഷ, ഔദ്യോഗിക തലക്കെട്ടല്ല / Explanatory translation, not the source title:**'
DATE_ML_LABEL = '**തീയതിയുടെ മലയാള വിവരണം / Date wording in Malayalam:**'


class Page:
    """Collects which translations one generated page used."""

    def __init__(self, tr: bilingual.Translations, labels: dict):
        self.tr = tr; self.labels = labels; self.used = []

    def L(self, key: str, **kw) -> str:
        kind, en = self.labels[key]
        en_text = en.format(**kw) if kw else en
        e = self.tr.get(f'scripts/build.py#{key}', en)
        if not e:
            return en_text
        self.used.append(e)
        return combine(kind, e['ml'].format(**kw) if kw else e['ml'], en_text)

    def T(self, key: str, en: str, kind: str = 'inline') -> str:
        e = self.tr.get(key, en)
        if not e:
            return en
        self.used.append(e)
        return combine(kind, e['ml'], en)

    def ml(self, key: str, en: str):
        e = self.tr.get(key, en)
        if e:
            self.used.append(e)
            return e['ml']
        return None

    def status(self):
        if not self.used:
            return None
        ai = any(e.get('ai_assisted', True) for e in self.used)
        reviewed = all(e.get('human_language_review') == 'approved' for e in self.used)
        return ai, reviewed

    def render(self, body: str, meta: dict | None = None) -> str:
        st = self.status()
        if st:
            ai, reviewed = st
            mm, me = NOTICE_METHOD[ai]; rm, re_ = NOTICE_REVIEW[reviewed]
            notice = (f'> മലയാളം ആദ്യം, ഇംഗ്ലീഷ് തുടർന്ന്. {mm}; {rm}. ഇംഗ്ലീഷ് പാഠമാണ് അടിസ്ഥാന ഡാറ്റ.\n>\n'
                      f'> Malayalam first, English second. {me} and {re_}. The English text remains the canonical data.')
            head, _, rest = body.strip().partition('\n\n')
            body = f'{head}\n\n{notice}\n\n{rest}'
            if meta is not None:
                meta = dict(meta)
                meta['translation_ml'] = ('ai_assisted' if ai else 'human_translated') + ('_human_review_recorded' if reviewed else '_human_review_pending')
        return (frontmatter(meta) if meta else '') + MARKER + '\n\n' + body.strip() + '\n'


def generated(body: str, meta: dict | None = None) -> str:
    return (frontmatter(meta) if meta else '') + MARKER + '\n\n' + body.strip() + '\n'


def make_outputs(data: dict | None = None, catalogues: list | None = None) -> tuple[dict[str,str], dict]:
    data = data if data is not None else load_data()
    catalogues = catalogues if catalogues is not None else bilingual.load_catalogues()
    labels = label_texts(data); tr = bilingual.Translations(catalogues)
    cfg=data['project']; ss=data['sources']; pp=data['periods']
    rr=data['records']; aa=data['audit']; cc=data['crosswalk']
    sd={s['id']:s for s in ss}; out={}; yy=years(cfg['annual_start'],cfg['annual_end'])
    by_year={n:[] for n in yy}
    for r in rr:
        for l in r['year_links']:
            if l['year'] in by_year:
                by_year[l['year']].append((r,l['role']))
    K=lambda coll,i,f: f'{coll}#{i}.{f}'
    rt=lambda pg,r: pg.T(K('data/records.json',r['id'],'title'),r['title'])
    pt=lambda pg,p: pg.T(K('data/periods.json',p['id'],'title'),p['title'])

    def source_refs(pg, ids: list[str], origin: str) -> str:
        return ', '.join(f'[{s}]({rel(f"sources/{s}.md",origin)})' for s in ids) or pg.L('source_refs.none')

    for s in ss:
        p=f'sources/{s["id"]}.md'; pg=Page(tr,labels); S=lambda f: K('data/sources.json',s['id'],f)
        body=f'# {s["id"]}: {s["title"]}\n\n'
        gloss=pg.ml(S('title'),s['title'])
        if gloss: body+=f'{GLOSS_LABEL} {gloss}\n\n'
        body+=f'{pg.L("source.creator")} {s["creator"]}  \n{pg.L("source.type")} `{s["source_kind"]}`  \n{pg.L("source.inspection")} `{s["inspection"]}`  \n{pg.L("source.accessed")} {s["accessed"]}\n\n'
        body+=f'{pg.L("source.link")}({s["url"]})\n\n'
        if s['doi']: body+=f'**DOI:** `{s["doi"]}`\n\n'
        if s['publication_year']: body+=pg.L('source.pubyear',year=s['publication_year'])+'\n\n'
        body+=f'{pg.L("source.h_inspected")}\n\n{s["inspected_locator"]}\n\n{pg.T(S("inspection_note"),s["inspection_note"],"block")}\n\n'
        body+=f'{pg.L("source.h_rights")}\n\n{pg.T(S("rights"),s["rights"],"block")}\n\n{pg.L("source.no_bundle")}\n\n'
        if s['alternative_urls']:
            body+=pg.L('source.h_alt')+'\n\n'+'\n'.join(f'- [{pg.L("source.alt_n",n=i+1)}]({u})' for i,u in enumerate(s['alternative_urls']))+'\n\n'
        uses=[r for r in rr if any(c['source']==s['id'] for c in r['support'])]
        body+=pg.L('source.h_linked')+'\n\n'+ ('\n'.join(f'- [{r["id"]}: {rt(pg,r)}](../records/{r["id"]}.md)' for r in uses) if uses else pg.L('source.no_linked'))
        out[p]=pg.render(body,{'id':s['id'],'human_review':s['human_review']})
    pg=Page(tr,labels)
    out['sources/README.md']=pg.render(pg.L('sources_readme.title')+'\n\n'+pg.L('sources_readme.intro')+'\n\n'+'\n'.join(f'- [{s["id"]}: {s["title"]}]({s["id"]}.md) (`{s["inspection"]}`)' for s in ss))
    for r in rr:
        p=f'records/{r["id"]}.md'; pg=Page(tr,labels); R=lambda f: K('data/records.json',r['id'],f)
        body=f'# {r["id"]}: {rt(pg,r)}\n\n{pg.T(R("claim"),r["claim"],"block")}\n\n'
        body+=f'{pg.L("record.evidence_type")} `{r["evidence_type"]}`  \n{pg.L("record.geo_relation")} `{r["scope_relation"]}`  \n{pg.L("record.places")} {"; ".join(r["places"]) or pg.L("record.global")}\n\n'
        body+=f'{pg.L("record.h_date")}\n\n```json\n{json.dumps(r["date"],ensure_ascii=False,indent=2)}\n```\n\n'
        dml=[(f,pg.ml(R(f'date.{f}'),r['date'][f])) for f in ('original_expression','datum','calendar') if isinstance(r['date'].get(f),str)]
        dml=[(f,m) for f,m in dml if m]
        if dml:
            body+=DATE_ML_LABEL+'\n\n'+'\n'.join(f'- `{f}`: {m}' for f,m in dml)+'\n\n'
        if r['other_dates']:
            body+=pg.L('record.other_dates')+'\n\n```json\n'+json.dumps(r['other_dates'],ensure_ascii=False,indent=2)+'\n```\n\n'
        body+=f'{pg.L("record.h_limitations")}\n\n{pg.T(R("caveat"),r["caveat"],"block")}\n\n'
        body+=pg.L('record.h_evidence')+'\n\n'+'\n'.join(f'- [{c["source"]}](../sources/{c["source"]}.md), {c["locator"]}. {pg.L("record.inspection")} `{sd[c["source"]]["inspection"]}`.' for c in r['support'])+'\n\n'
        body+=pg.L('record.h_nav')+'\n\n'+'; '.join(f'[{x}](../periods/{x}.md)' for x in r['periods'])+'\n\n'
        if r['year_links']:
            body+='; '.join(f'[{label(x["year"])}]({rel(year_path(x["year"]),p)}): {pg.L("roles."+x["role"])}' for x in r['year_links'])+'\n\n'
        body+=f'{pg.L("record.h_review")}\n\n{pg.T(R("authoring"),r["authoring"],"block")}\n\n{pg.L("record.human_review")} {r["human_review"]}. {pg.L("record.created_updated")} {r["created"]} / {r["updated"]}.\n\n{pg.T(R("rights"),r["rights"],"block")}'
        out[p]=pg.render(body,{'id':r['id'],'status':r['status'],'human_review':r['human_review']})
    pg=Page(tr,labels)
    out['records/README.md']=pg.render(pg.L('records_readme.title')+'\n\n'+pg.L('records_readme.intro')+'\n\n'+'\n'.join(f'- [{r["id"]}: {rt(pg,r)}]({r["id"]}.md)' for r in rr))
    for p in pp:
        path=f'periods/{p["id"]}.md'; pg=Page(tr,labels); P=lambda f: K('data/periods.json',p['id'],f)
        body=f'# {p["id"]}: {pt(pg,p)}\n\n{pg.L("period.window")} {pg.T(P("display_window"),p["display_window"],"line")}.\n\n{pg.L("period.question")} {pg.T(P("central_question"),p["central_question"],"line")}\n\n'
        body+=pg.L('period.h_evidence')+'\n\n'+pg.T(P('established_in_this_pass'),p['established_in_this_pass'],'block')+'\n\n'
        body+=pg.L('period.source_routes')+' '+source_refs(pg,p['sources'],path)+'.\n\n'
        body+=pg.L('period.h_not')+'\n\n'+pg.T(P('limitations'),p['limitations'],'block')+'\n\n'
        body+=pg.L('period.h_tasks')+'\n\n'+'\n'.join(f'- [ ] {pg.T(P(f"research_tasks[{i}]"),t,"list")}' for i,t in enumerate(p['research_tasks']))+'\n\n'
        body+=pg.L('period.h_records')+'\n\n'
        ps=[r for r in rr if p['id'] in r['periods']]
        body+=('\n'.join(f'- [{r["id"]}: {rt(pg,r)}](../records/{r["id"]}.md)' for r in ps) if ps else pg.L('period.no_records'))+'\n\n'
        body+=pg.L('period.h_coverage')+'\n\n'+pg.L('period.coverage')
        out[path]=pg.render(body,{'id':p['id'],'kind':p['kind'],'coverage':'seed_or_open_dossier'})
    pg=Page(tr,labels)
    out['periods/README.md']=pg.render(pg.L('periods_readme.title')+'\n\n'+pg.L('periods_readme.intro')+'\n\n'+'\n'.join(f'- [{p["id"]}: {pt(pg,p)}]({p["id"]}.md)' for p in pp))
    for i,y in enumerate(yy):
        p=year_path(y).as_posix(); entries=by_year[y]; pg=Page(tr,labels)
        status='seed_index' if entries else 'unresearched'
        body=f'# {label(y)}\n\n'
        nav=[]
        if i: nav.append(f'[← {label(yy[i-1])}]({rel(year_path(yy[i-1]),p)})')
        nav.append(pg.L('year.index'))
        if i+1<len(yy): nav.append(f'[{label(yy[i+1])} →]({rel(year_path(yy[i+1]),p)})')
        body+=' · '.join(nav)+'\n\n'
        body+=pg.L('year.coverage')+' '+(pg.L('year.coverage_seed') if entries else pg.L('year.coverage_none'))+'\n\n'
        if y == cfg['annual_end']:
            body+=pg.L('year.partial',as_of=cfg['as_of'])+'\n\n'
        for role in ROLES:
            rs=[r for r,k in entries if k==role]
            if rs:
                body+=f'## {pg.L("roles."+role)}\n\n'
                for r in rs:
                    body+=f'- [{r["id"]}: {rt(pg,r)}](../../records/{r["id"]}.md). {source_refs(pg,[x["source"] for x in r["support"]],p)}.\n'
                body+='\n'
        body+=pg.L('year.h_wider')+'\n\n'
        ps=[x for x in pp if x['annual_span'] and x['annual_span'][0] <= y <= x['annual_span'][1]]
        body+=('\n'.join(f'- [{x["id"]}: {pt(pg,x)}](../../periods/{x["id"]}.md)' for x in ps) if ps else pg.L('year.period_index'))+'\n\n'
        body+=pg.L('year.h_interp')+'\n\n'+pg.L('year.interp1')+'\n\n'+pg.L('year.interp2')
        out[p]=pg.render(body,{'year':abs(y),'era':'BCE' if y<0 else 'CE','status':status,'as_of':cfg['as_of']})
    # Era-specific navigation lists keep the root year index readable.
    for era,group in [('BCE',[x for x in yy if x<0]),('CE',[x for x in yy if x>0])]:
        pg=Page(tr,labels)
        body=pg.L('era_index.title',era=era)+'\n\n'+pg.L('era_index.intro')+'\n\n'
        for k in range(0,len(group),100):
            block=group[k:k+100]
            body+=pg.L('era_index.range',start=label(block[0]),end=label(block[-1]))+'\n\n'+' · '.join(f'[{abs(x)}]({abs(x):04d}.md)' for x in block)+'\n\n'
        out[f'years/{era}/README.md']=pg.render(body)
    pg=Page(tr,labels)
    out['years/README.md']=pg.render(pg.L('years_readme.title')+'\n\n'+pg.L('years_readme.p1',n=f'{len(yy):,}',start=label(yy[0]),end=label(yy[-1]))+'\n\n'+pg.L('years_readme.nav')+'\n\n'+pg.L('years_readme.p2'))
    pg=Page(tr,labels)
    auditbody=pg.L('audit.title')+'\n\n'+pg.L('audit.intro')+'\n\n'
    for a in aa:
        A=lambda f: K('data/audit.json',a['id'],f)
        auditbody+=f'## {a["id"]}: {pg.L("verdict."+a["verdict"])}\n\n{pg.L("audit.earlier")} {pg.T(A("earlier_claim"),a["earlier_claim"],"line")}\n\n{pg.L("audit.treatment")} {pg.T(A("corrected_treatment"),a["corrected_treatment"],"line")}\n\n{pg.L("audit.route")} {source_refs(pg,a["sources"],"audit/CHAT_AUDIT.md")}\n\n'
    auditbody+=pg.L('audit.h_crosswalk')+'\n\n'+pg.L('audit.table_head')+'\n|---|---|---|---|\n'
    for c in cc:
        C=lambda f: K('data/prior_chapter_crosswalk.json',c['chapter'],f)
        auditbody+=f'| {c["chapter"]} | {pg.T(C("title"),c["title"])} | {c["dossiers"]} | {pg.T(C("assessment"),c["assessment"])} |\n'
    out['audit/CHAT_AUDIT.md']=pg.render(auditbody)
    past={y for y,v in by_year.items() if any(k!='research_history' for _,k in v)}
    research_only={y for y,v in by_year.items() if v and y not in past}
    depth=Counter(INSPECTION_DEPTH.get(s['inspection'],'unmapped') for s in ss)
    cited={c['source'] for r in rr for c in r['support']}
    links=[l for r in rr for l in r['year_links'] if l['year'] in by_year]
    stats=dict(as_of=cfg['as_of'],annual_files=len(yy),annual_pages_with_year_specific_seeds=sum(bool(v) for v in by_year.values()),
       annual_pages_without_year_specific_seeds=sum(not v for v in by_year.values()),canonical_records=len(rr),source_records=len(ss),
       era_dossiers=sum(p['kind']=='prehistory_and_deep_time' for p in pp),documentary_dossiers=sum(p['kind']!='prehistory_and_deep_time' for p in pp),
       audit_items=len(aa),prior_chapters_mapped=len(cc),human_reviewed_records=sum(r['human_review']=='approved' for r in rr),
       sources_by_inspection=dict(Counter(s['inspection'] for s in ss)),licensed_boundary_geometry_present=False,
       third_party_fulltexts_bundled=0,completed_collection_inventories=0,whole_web_completeness='not_claimed')
    # Separate measures. Counts below are additions; the keys above keep their meaning.
    stats.update(
       annual_year_links_total=len(links),
       annual_year_links_by_role={k:sum(1 for l in links if l['role']==k) for k in ROLES},
       records_with_annual_links=sum(1 for r in rr if any(l['year'] in by_year for l in r['year_links'])),
       annual_pages_with_past_event_links=len(past),
       annual_pages_with_only_research_history_links=len(research_only),
       sources_cited_by_records=len(cited & set(sd)),
       sources_by_inspection_depth={k:depth[k] for k in DEPTH_ORDER},
       sources_inspected_at_passage_or_full_text=depth['passage']+depth['full_text'],
       human_reviewed_sources=sum(s['human_review']=='approved' for s in ss),
       translation={'ml':dict(bilingual.coverage(data,catalogues,labels),
            note='Translation coverage only. It is not source inspection or scholarly review. Missing translations stay listed as missing.')})
    out['coverage/stats.json']=json.dumps(stats,ensure_ascii=False,indent=2)+'\n'
    c=io.StringIO(); w=csv.writer(c,lineterminator="\n"); w.writerow(['era','year','file','year_specific_seed_links','status','past_event_links','research_history_links'])
    for y in yy:
        v=by_year[y]; rh=sum(1 for _,k in v if k=='research_history')
        w.writerow(['BCE' if y<0 else 'CE',abs(y),year_path(y).as_posix(),len(v),'seed_index' if v else 'unresearched',len(v)-rh,rh])
    out['coverage/year-status.csv']=c.getvalue()
    pg=Page(tr,labels); t=stats['translation']['ml']
    rows=[('coverage.r1',f'{len(yy):,}'),('coverage.r2',stats['annual_pages_with_year_specific_seeds']),('coverage.r3',f"{stats['annual_pages_without_year_specific_seeds']:,}"),
          ('coverage.r4',len(rr)),('coverage.r5',len(ss)),('coverage.r6',stats['era_dossiers']),('coverage.r7',stats['documentary_dossiers']),
          ('coverage.r8',stats['human_reviewed_records']),('coverage.r9',0),('coverage.r10',0),('coverage.r11',0)]
    sep=[('coverage.year_links',stats['annual_year_links_total']),('coverage.records_with_links',stats['records_with_annual_links']),
         ('coverage.past_event_pages',stats['annual_pages_with_past_event_links']),('coverage.research_only_pages',stats['annual_pages_with_only_research_history_links']),
         ('coverage.sources_cited',stats['sources_cited_by_records']),('coverage.sources_passage',stats['sources_inspected_at_passage_or_full_text']),
         ('coverage.sources_shallow',depth['metadata']+depth['not_accessed']),('coverage.sources_reviewed',stats['human_reviewed_sources']),
         ('coverage.ml_fields',pg.L('coverage.of',n=t['data_fields_current'],total=t['data_fields_total'])),
         ('coverage.ml_labels',pg.L('coverage.of',n=t['generator_labels_current'],total=t['generator_labels_total'])),
         ('coverage.ml_reviewed',t['data_fields_human_reviewed']+t['generator_labels_human_reviewed'])]
    body=pg.L('coverage.title',version=cfg['version'])+'\n\n'+pg.L('coverage.asof',as_of=cfg['as_of'])+'\n\n'
    body+=pg.L('coverage.th')+'\n|---|---:|\n'+''.join(f'| {pg.L(k)} | {v} |\n' for k,v in rows)+'\n'
    body+=pg.L('coverage.p1')+'\n\n'+pg.L('coverage.p2')+'\n\n'
    body+=pg.L('coverage.h_separate')+'\n\n'+pg.L('coverage.th')+'\n|---|---:|\n'+''.join(f'| {pg.L(k)} | {v} |\n' for k,v in sep)+'\n'
    body+=pg.L('coverage.p_separate')+'\n\n'+pg.L('coverage.links')
    out['coverage/README.md']=pg.render(body)
    return out,stats


def orphaned_outputs(out: dict) -> list[str]:
    """Generated-marker Markdown files under generated folders that no canonical item produces any more."""
    found=[]
    for d in GENERATED_DIRS:
        for f in sorted((ROOT/d).rglob('*.md')) if (ROOT/d).is_dir() else []:
            p=f.relative_to(ROOT).as_posix()
            if p not in out and MARKER in f.read_text(encoding='utf-8'):
                found.append(p)
    return found


def main() -> int:
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--check',action='store_true',help='Compare generated views without changing files.')
    args=parser.parse_args()
    out,stats=make_outputs()
    mismatches=[p for p,t in out.items() if not (ROOT/p).exists() or (ROOT/p).read_text(encoding='utf-8')!=t]
    orphans=orphaned_outputs(out)
    if args.check:
        if mismatches or orphans:
            if mismatches: print('Stale/missing generated views:',*mismatches[:15],sep='\n')
            if orphans: print('Orphaned generated views with no canonical source:',*orphans,sep='\n')
            return 1
        print(f'All {len(out)} generated files match canonical data.')
        return 0
    # Preflight ALL outputs before any write. Never overwrite hand-authored Markdown.
    for p in out:
        f=ROOT/p
        if f.exists() and f.suffix=='.md' and MARKER not in f.read_text(encoding='utf-8'):
            print(f'Refusing to overwrite non-generated Markdown: {p}. Nothing was written.',file=sys.stderr)
            return 2
    for p,text in out.items():
        f=ROOT/p; f.parent.mkdir(parents=True,exist_ok=True)
        if f.exists() and f.read_text(encoding='utf-8')==text: continue
        tmp=f.with_suffix(f.suffix+'.tmp'); tmp.write_text(text,encoding='utf-8',newline='\n'); tmp.replace(f)
    print(json.dumps(stats,indent=2,ensure_ascii=False))
    print(f'Built {len(out)} generated files. No network requests made.')
    if orphans:
        print('Orphaned generated views were left in place; remove them after checking:',*orphans,sep='\n')
        return 1
    return 0

if __name__=='__main__':
    raise SystemExit(main())
