"""Continuation: new inspected images, fresh revision audit, unchanged old batches."""
from collections import Counter
from pathlib import Path
import sys

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
from pallet.cluster_targets import digest, protected_snapshot
from pallet.mask_quota_saved_extension import file_inventory
from pallet.mask_template_refined import read_jsonl
from scripts import build_mask_under50_requests as previous

OUT = PROJECT/'outputs/pallet_mask_under50_requests_v2'
SOURCES = PROJECT/'outputs/pallet_mask_continuation_sources_v2'


def context():
    # The old implementation is reused without editing its pinned file or
    # source snapshot. Only its fresh source context is supplied here.
    result = previous.read(SOURCES/'audit.json')
    previous.require(result['state'].startswith('passed_event_provenance'), 'Fresh actual-save provenance required')
    previous.require(digest(SOURCES/'private/source_catalog.jsonl') == result['source_catalog_sha256'], 'Fresh catalog changed')
    # Reimplement only the initial fingerprint and source source selection:
    # the remaining protection logic is isolated in this new context, not a
    # mutable global SOURCE replacement inside the sealed quality module.
    from contextlib import closing
    from collections import defaultdict
    import json
    import sqlite3
    from pallet.mask_quality_recovery import POSE, GALLERY, fingerprint
    from pallet.mask_quota_saved_extension import load_formal_evidence
    from pallet.mask_remaining_classes import confirmed, original_rectangle
    from pallet.mask_template_refined import QUARANTINE
    from scripts.build_mask_template_requests import database_fingerprint
    previous.require(fingerprint(POSE) == result['pose_fingerprint'] and fingerprint(GALLERY) == result['gallery_fingerprint'],
        'New saves arrived after this frozen continuation audit; create a new audit, do not overwrite it')
    manifest = previous.read(previous.PARENT/'manifest.json')
    formal, rows, evidence = load_formal_evidence(manifest)
    catalog = read_jsonl(SOURCES/'private/source_catalog.jsonl')
    counts = Counter(r['row']['final_class_id'] for r in catalog)
    previous.require(tuple(c for c in range(1, 23) if counts[c] < 50) == previous.CLASSES, 'Under50 class scope changed')
    with closing(sqlite3.connect(POSE.as_uri()+'?mode=ro', uri=True)) as db:
        current = {k: json.loads(raw) for k, raw in db.execute('SELECT target_key,payload FROM annotations')}
        history = defaultdict(list)
        for key, raw in db.execute('SELECT target_key,payload FROM events ORDER BY id'):
            history[key].append(json.loads(raw))
    protected = set(QUARANTINE) | {r['target_key'] for r in catalog}
    protected.update(p['target_key'] for p in read_jsonl(previous.PARENT/'proposals.jsonl'))
    for key in set(current) | set(history):
        values = history[key]+([current[key]] if key in current else [])
        if key not in current or any(v.get('state') in ('deleted', 'deferred', 'confirmed') or confirmed(v)
                or not original_rectangle(v.get('polygon'), rows[key]) for v in values):
            protected.add(key)
    inventories = {}
    for pattern in ('requests.jsonl', 'shortlist.jsonl'):
        for path in sorted((PROJECT/'outputs').rglob(pattern)):
            if path.is_relative_to(OUT):
                continue
            protected.update(r['target_key'] for r in read_jsonl(path) if r.get('target_key') in rows)
            inventories[str(path.relative_to(PROJECT))] = digest(path)
    image_hashes = {digest(formal/name) for name in {rows[k]['image'] for k in protected}}
    return dict(formal=formal, rows=rows, evidence=evidence, current=current, history=history,
        protected=protected, frames={rows[k]['frame_id'] for k in protected}, protected_image_hashes=image_hashes,
        counts=counts, prior_inventories=inventories,
        fingerprints={str(p.relative_to(PROJECT)): database_fingerprint(p) for p in (POSE, GALLERY)},
        formal_protected=protected_snapshot(formal), formal_sha=manifest['formal_manifest_sha256'])


def setup():
    previous.OUT = OUT
    previous.context = context


def refresh_after_real_saves():
    """Preserve old staging evidence before rebinding this still-unbuilt pack."""
    from pallet.pose_review_geometry import canonical
    from scripts.build_mask_template_requests import database_fingerprint
    from pallet.mask_quality_recovery import POSE, GALLERY
    path = OUT/'input_manifest.json'
    previous.require(not (OUT/'manifest.json').exists(), 'Completed pack is immutable')
    backup = OUT/'internal/input_manifest_before_real10_completion.json'
    previous.require(not backup.exists(), 'Source refresh is exclusive; preserve earlier refreshes')
    data = context(); inputs = previous.read(path)
    before = path.read_bytes()
    with backup.open('xb') as stream:
        stream.write(before)
    inputs.update(database_fingerprints=data['fingerprints'], actual_counted_saved_basis=sum(data['counts'].values()),
        actual_class_counts=dict(data['counts']), continuation_source_audit_sha256=digest(SOURCES/'audit.json'),
        continuation_source_catalog_sha256=digest(SOURCES/'private/source_catalog.jsonl'),
        continuation_source_directory=str(SOURCES.relative_to(PROJECT)),
        previous10_actual_completed_saves_at_refresh=10, previous_staging_evidence_sha256=digest(backup),
        continuation_builder_sha256=digest(__file__),
        source_quality_audit_sha256=digest(previous.QUALITY/'independent_verification.json'))
    # All selected keys remain required to be unreviewed and absent from the
    # complete refreshed protection set. This does not promote any saved draft
    # into a propagation seed or training record.
    for record in read_jsonl(OUT/'internal/shortlist.jsonl'):
        previous.require(record['target_key'] not in data['protected'] and record['source']['frame_id'] not in data['frames'],
            'A staged target became protected; do not issue it')
    path.write_bytes(canonical(inputs)+b'\n')
    previous.require(data['fingerprints'] == {str(p.relative_to(PROJECT)): database_fingerprint(p) for p in (POSE, GALLERY)},
        'Human stores changed while refreshing this prebuild receipt')


def finalize_unsealed_binding():
    """Seal-ready explicit v2 source binding; no geometry or source is changed."""
    from pallet.pose_review_geometry import canonical
    previous.require(not (OUT/'verification.json').exists() and not (OUT/'independent_verification.json').exists(),
        'Never edit a sealed task publication')
    backup = OUT/'internal/pre_final_binding'
    previous.require(not backup.exists(), 'Keep all prior binding revisions')
    backup.mkdir(mode=0o700)
    for name in ('input_manifest.json', 'manifest.json', 'proposals.jsonl', 'requests.jsonl'):
        (backup/name).write_bytes((OUT/name).read_bytes())
    inputs = previous.read(OUT/'input_manifest.json')
    inputs.update(source_audit_sha256=digest(SOURCES/'audit.json'), continuation_builder_sha256=digest(__file__))
    (OUT/'input_manifest.json').write_bytes(canonical(inputs)+b'\n')
    for name in ('proposals.jsonl', 'requests.jsonl'):
        records = read_jsonl(OUT/name)
        for record in records:
            record['preannotation']['input_manifest_sha256'] = digest(OUT/'input_manifest.json')
        (OUT/name).write_bytes(b''.join(canonical(record)+b'\n' for record in records))
    manifest = previous.read(OUT/'manifest.json')
    manifest.update(generation_code_sha256=digest(__file__), continuation_builder_sha256=digest(__file__),
        reused_under50_export_adapter_sha256=digest(Path(previous.__file__)),
        source_audit_sha256=digest(SOURCES/'audit.json'), input_manifest_sha256=digest(OUT/'input_manifest.json'),
        proposals_sha256=digest(OUT/'proposals.jsonl'), requests_sha256=digest(OUT/'requests.jsonl'),
        pre_final_binding_evidence_sha256=file_inventory(backup))
    (OUT/'manifest.json').write_bytes(canonical(manifest)+b'\n')


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--stage', choices=('review', 'refresh', 'build', 'finalize'), required=True)
    parser.add_argument('--decisions', type=Path)
    args = parser.parse_args(); setup()
    if args.stage == 'review':
        previous.review()
        from pallet.pose_review_geometry import canonical
        inputs = previous.read(OUT/'input_manifest.json')
        inputs.update(continuation_source_audit_sha256=digest(SOURCES/'audit.json'),
            continuation_source_catalog_sha256=digest(SOURCES/'private/source_catalog.jsonl'),
            continuation_source_directory=str(SOURCES.relative_to(PROJECT)),
            declared_previous10_completed_but_actual_saves_at_staging=0,
            current_source_revisions_not_recounted_as_new_distinct_images=True,
            continuation_builder_sha256=digest(__file__))
        (OUT/'input_manifest.json').write_bytes(canonical(inputs)+b'\n')
    elif args.stage == 'refresh':
        refresh_after_real_saves()
    elif args.stage == 'finalize':
        finalize_unsealed_binding()
    else:
        previous.build(args.decisions)
        from pallet.pose_review_geometry import canonical
        manifest = previous.read(OUT/'manifest.json')
        manifest.update(continuation_builder_sha256=digest(__file__),
            source_audit_sha256=digest(SOURCES/'audit.json'),
            continuation_source_audit_sha256=digest(SOURCES/'audit.json'),
            continuation_source_catalog_sha256=digest(SOURCES/'private/source_catalog.jsonl'))
        (OUT/'manifest.json').write_bytes(canonical(manifest)+b'\n')
