#!/usr/bin/env python3
"""Add deterministic document-original contracts to a disposable V5 fixture."""
from __future__ import annotations

import argparse
import sqlite3
from pathlib import Path


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--db", type=Path, required=True)
    parser.add_argument("--root", type=Path, required=True)
    args = parser.parse_args()
    args.root.mkdir(parents=True, exist_ok=True, mode=0o700)
    (args.root / "reviewed.pdf").write_bytes(b"%PDF-1.7\nSYNTHETIC ORIGINAL\n")
    (args.root / "reviewed.png").write_bytes(b"\x89PNG\r\n\x1a\nSYNTHETIC IMAGE")
    (args.root / "unsupported.pdf").write_bytes(b"SYNTHETIC UNSUPPORTED")
    rows = [
        ("synthetic-reviewed.pdf", "reviewed.pdf", "pdf", "SYNTHETIC_6E4B", "SYNTHETIC_CLINIC", "geprueft", "2026-06-14", "SYNTHETIC SEARCHABLE CONTENT\nSecond synthetic section", 1, "s6e4b-1"),
        ("synthetic-reviewed.png", "reviewed.png", "image", "SYNTHETIC_6E4B", "SYNTHETIC_CLINIC", "geprueft", "2026-06-13", "SYNTHETIC IMAGE CONTENT", 1, "s6e4b-2"),
        ("synthetic-pending.pdf", "reviewed.pdf", "pdf", "SYNTHETIC_6E4B", "SYNTHETIC_CLINIC", "nicht_geprueft", "2026-06-12", "SYNTHETIC PENDING CONTENT", 1, "s6e4b-3"),
        ("synthetic-unsupported.pdf", "unsupported.pdf", "pdf", "SYNTHETIC_6E4B", "SYNTHETIC_CLINIC", "geprueft", "2026-06-11", "", 1, "s6e4b-4"),
        ("synthetic-missing.pdf", "missing.pdf", "pdf", "SYNTHETIC_6E4B", "SYNTHETIC_CLINIC", "geprueft", "2026-06-10", "SYNTHETIC MISSING ORIGINAL", 1, "s6e4b-5"),
    ]
    rows.extend(
        (
            f"synthetic-page-{index:02d}.pdf", f"missing-page-{index:02d}.pdf", "pdf",
            "SYNTHETIC_PAGED", "SYNTHETIC_CLINIC", "geprueft",
            f"2026-05-{index:02d}", f"SYNTHETIC PAGED SEARCHABLE CONTENT {index:02d}",
            1, f"s6a1-page-{index:02d}",
        )
        for index in range(1, 28)
    )
    connection = sqlite3.connect(args.db)
    try:
        connection.executemany(
            """INSERT INTO dokumente(
                   datei_name,dateipfad,daten_typ,kategorie,institution,review_status,
                   document_date,extrahierte_inhalte,groessekbytes,datei_hash
               ) VALUES(?,?,?,?,?,?,?,?,?,?)""",
            rows,
        )
        connection.execute(
            """CREATE VIRTUAL TABLE IF NOT EXISTS health_document_fts USING fts5(
                   document_id UNINDEXED, chunk_no UNINDEXED, heading, content,
                   section_path, page_ref, text
               )"""
        )
        for document_id, content in connection.execute(
            """SELECT id,extrahierte_inhalte FROM dokumente
               WHERE review_status='geprueft' AND trim(COALESCE(extrahierte_inhalte,''))<>''
               ORDER BY id"""
        ):
            connection.execute(
                """INSERT INTO health_document_fts(
                       document_id,chunk_no,heading,content,section_path,page_ref,text
                   ) VALUES(?,1,'Synthetischer Abschnitt',?,'1','1',?)""",
                (str(document_id), content, content),
            )
        first_document = connection.execute(
            "SELECT id FROM dokumente WHERE datei_hash='s6e4b-1'"
        ).fetchone()
        if first_document:
            connection.execute(
                "UPDATE laborwerte SET canonical_document_id=? WHERE parameter_name='C-Reaktives Protein (CRP)'",
                (first_document[0],),
            )
            connection.execute(
                """INSERT INTO laborwerte(
                       parameter_name,wert,einheit,reference_min,reference_max,
                       abnahme_datum,befund_datum,wert_original,quelle,validierungsstatus,
                       source_type,reference_range_source,verified_against_original,
                       provenance_note,ermittlung_datum,canonical_document_id
                   ) VALUES('D-Dimer','240','µg/L','0','500','2026-06-14','2026-06-14',
                            '240','synthetic laboratory fixture','validiert','synthetic',
                            'scanned_original',1,'Synthetic test row','2026-06-15T12:00:00+00:00',?)""",
                (first_document[0],),
            )
        connection.execute(
            """INSERT INTO arztbesuche(datum,arzt,klinik,grund,notizen)
               VALUES('2026-06-14','SYNTHETIC_PRACTITIONER','SYNTHETIC_CLINIC',
                      'SYNTHETIC_FOLLOW_UP','synthetic appointment fixture')"""
        )
        connection.commit()
    finally:
        connection.close()


if __name__ == "__main__":
    main()
