"""Neutral T08 corpus/artifact fixture; never reads a private or production corpus."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sqlite3
import sys
from pathlib import Path
sys.stdout.reconfigure(encoding="utf-8")

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
if os.environ.get("HJ_TEST_APSW_PATH"):
    sys.path.insert(0, os.environ["HJ_TEST_APSW_PATH"])


def write(path, value):
    path.write_text(json.dumps(value, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8")


def build(out):
    from hanji_core.contracts import CONTRACT_REVISION, sha256_utf8
    from hanji_core.index.runtime import file_sha256
    from hanji_core.index.t02_inputs import T02Inputs
    out.mkdir(parents=True, exist_ok=True)
    source = out / "synthetic.sqlite"
    bodies = {1: ("book-a", 1, "甲嚴 嵩乙𠀀é\r\n錄之之"), 2: ("book-a", 2, "严嵩所记甲乙錄"), 3: ("book-b", 1, "发發髮庙祀之禮")}
    meta = {"built_at": "T08-neutral/1", "article_count": "3", "doc_count": "3", "book_count": "2", "char_count": str(sum(len(r[2]) for r in bodies.values()))}
    db = sqlite3.connect(source)
    db.execute("CREATE TABLE metadata(key TEXT PRIMARY KEY,value TEXT)")
    db.executemany("INSERT INTO metadata VALUES(?,?)", meta.items())
    db.execute("CREATE TABLE docs(docid INTEGER PRIMARY KEY,book_base TEXT,article_no INTEGER,body TEXT,title TEXT,rel_path TEXT,source TEXT,char_count INTEGER)")
    db.executemany("INSERT INTO docs VALUES(?,?,?,?,?,?,?,?)", [(key,*row,"中性甲书·卷"+str(row[1]),"synthetic","T08-neutral",len(row[2])) for key,row in bodies.items()])
    db.execute("CREATE VIRTUAL TABLE docs_fts USING fts5(body,content='docs',content_rowid='docid',tokenize='trigram')")
    db.execute("INSERT INTO docs_fts(docs_fts) VALUES('rebuild')")
    db.commit();db.close()
    corpus = {"corpus_id":"fixture-t08","corpus_revision":"fixture-corpus/1","db_bytes":source.stat().st_size,"db_path":str(source),"db_sha256":file_sha256(source),"metadata":meta}
    books = [{"book_id":book,"display_name":"中性甲书" if book=='book-a' else '中性乙书',"codepoints":sum(len(row[2]) for row in bodies.values() if row[0]==book),"name_provenance":"synthetic-label"} for book in ['book-a','book-b']]
    catalog = {"artifact":"hj-catalog","artifact_version":1,"catalog_revision":"fixture-catalog/1","corpus":corpus,
               "integrity":{"char_count_violations":[],"metadata_matches":{"fixture":True},"units_scanned":3,"books_scanned":2},"books":books,
               "units":[{"docid":key,"book_id":row[0],"article_no":row[1],"codepoints":len(row[2]),"body_sha256":sha256_utf8(row[2]),"title":"中性甲书·卷"+str(row[1]),"volume_label":"synthetic","volume_no":row[1],"name_provenance":"synthetic-label"} for key,row in bodies.items()]}
    catalog_path=out/'hj_catalog_v1.json';write(catalog_path,catalog)
    rules={"artifact":"hj-script-rules","artifact_version":1,"contract_revision":CONTRACT_REVISION,"rules_revision":"fixture-rules/1","legend":{"F0":"fixture:direct"},"counts":{},"pairs":[[a,b,'F0'] for a,b in [('严','嚴'),('嚴','严'),('录','錄'),('錄','录'),('发','發'),('发','髮'),('發','发'),('髮','发')]]}
    rules_path=out/'script_rules_v1.json';write(rules_path,rules)
    manifest={"artifact_set":"hanji-t02-catalog","manifest_version":1,"corpus":corpus,"generator":{"source_commit":"T08-neutral-fixture","module":"T02-format-fixture"},"artifacts":{catalog_path.name:{"bytes":catalog_path.stat().st_size,"sha256":file_sha256(catalog_path),"catalog_revision":catalog['catalog_revision']}}}
    manifest_path=out/'MANIFEST_hanji_t02_v1.json';write(manifest_path,manifest)
    with T02Inputs(catalog_path,rules_path,manifest_path,source,expected_manifest_sha256=file_sha256(manifest_path),expected_rules_sha256=file_sha256(rules_path)) as inputs:
        index_manifest=inputs.build(out/'synthetic-index.sqlite',index_revision='fixture-index/1',source_commit='T08-neutral-fixture')
    env={"HJ_CORPUS_DB":str(source),"HJ_HITS2_CATALOG":str(catalog_path),"HJ_HITS2_RULES":str(rules_path),"HJ_HITS2_MANIFEST":str(manifest_path),"HJ_HITS2_MANIFEST_SHA":file_sha256(manifest_path),"HJ_HITS2_RULES_SHA":file_sha256(rules_path),"HJ_HITS2_INDEX_MANIFEST":str(index_manifest),"HJ_HITS2_APSW_PATH":os.environ.get('HJ_TEST_APSW_PATH',''),"HJ_HITS2_WORKERS":"2"}
    versions=json.loads(Path(index_manifest).read_text(encoding='utf-8'))['versions']
    value={"env":env,"versions":versions,"bodies":{str(k):r[2] for k,r in bodies.items()},"source_refs":{str(u['docid']):{k:corpus[k] for k in ('corpus_id','corpus_revision')}|{k:u[k] for k in ('book_id','docid','body_sha256')} for u in catalog['units']}}
    write(out/'fixture.json',value)
    return value


if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('--out',type=Path,required=True);args=parser.parse_args()
    result=build(args.out)
    print(json.dumps({"fixture":str(args.out/'fixture.json'),"versions":result['versions']},ensure_ascii=False))
