"""Read-only empty-sidecar and protected-source acceptance for an explicit publication."""
from contextlib import closing
from datetime import datetime,timezone
import json
from pathlib import Path
import sqlite3
import sys

PROJECT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(PROJECT));sys.path.insert(0,str(PROJECT/'scripts'))
from pallet.cluster_targets import digest,protected_snapshot
from pallet.mask_quota_saved_extension import file_inventory,load_formal_evidence
from pallet.mask_review_preservation import saved_revision_preserved,event_prefix_preserved
from pallet.pose_review_masks import MaskSuggestions
from pallet.pose_review_geometry import canonical
from review_http_pool import ReadOnlyHTTP

ROOT=PROJECT/'outputs/pallet_mask_remaining_round4_v1'
TASKS=PROJECT/'outputs/pallet_mask_preannotated_requests_v2'
OUT=PROJECT/'outputs/pallet_mask_remaining_round4_deployment_v1'
VERSION=14


def read(path):return json.loads(Path(path).read_text())


def sidecar():
    result=OUT/'pose_sidecar_acceptance.json'
    if result.exists():raise ValueError('Preserve completed sidecar acceptance')
    config=PROJECT/'configs/active_mask_template_proposals.json';settings=read(config)
    assert settings['version']==VERSION and settings['count']==0 and settings['proposals_sha256']==digest(ROOT/'new_proposals.jsonl')
    assert (ROOT/'new_proposals.jsonl').read_bytes()==b''
    formal,rows,_=load_formal_evidence(read(ROOT/'manifest.json'))
    with closing(sqlite3.connect((PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3').as_uri()+'?mode=ro',uri=True)) as db:
        poses={k:json.loads(raw) for k,raw in db.execute('SELECT target_key,payload FROM annotations')}
    class Store:
        def get(self,key):return poses.get(key)
    suggestions=MaskSuggestions(config,formal);assert suggestions.load()=={} and suggestions.fingerprint is not None
    tasks={p['target_key'] for p in map(json.loads,(TASKS/'proposals.jsonl').read_text().splitlines())}
    assert all(suggestions.get(k,poses.get(k),rows[k],Store()) is None for k in tasks)
    password=(PROJECT/'outputs/pallet_pose_human_review_v1/access_key.txt').read_text().strip();checks=[]
    access=read(PROJECT/'outputs/pallet_pose_review_managed_v1/public_access.json');key=next(iter(tasks))
    for base in (access['local_url'],access['public_url']):
        with ReadOnlyHTTP(base) as client:
            client.login(password);assert client.get('/api/queue?state=mask_proposal').json()['keys']==[]
            assert client.get('/api/bootstrap').json()['stats']['total']==12344
            detail=client.get('/api/targets/'+key).json();assert detail.get('mask_suggestion') is None and detail['review']==poses.get(key)
            checks.append(dict(url=base,available_strict_suggestions=0,old_candidates_not_reissued=True,assistant_tasks_excluded=True,original_review_unchanged=True))
    value=dict(state='passed',checks=checks,no_strict_pass_means_empty_sidecar=True,preannotations_not_pose_or_template_input=True,
        production_annotation_writes=0,automatic_training_eligible=False,robot_command_eligible=False)
    result.write_bytes(canonical(value)+b'\n');print(json.dumps(value),flush=True)


def sources():
    result=OUT/'post_publication_source_integrity.json'
    if result.exists():raise ValueError('Preserve completed source protection acceptance')
    manifest=read(ROOT/'manifest.json');formal,rows,_=load_formal_evidence(manifest)
    for name,h in read(ROOT/'artifact_hashes.json').items():assert digest(ROOT/name)==h,name
    for name,h in manifest['frozen_code_sha256'].items():assert digest(PROJECT/name)==h,name
    assert len(rows)==12344 and len(protected_snapshot(formal))==20768
    assert protected_snapshot(formal)==read(ROOT/'protected_formal_before.json')==read(ROOT/'protected_formal_after.json')
    assert file_inventory(PROJECT/'configs')==read(OUT/'activation.json')['config_after']
    old=read(OUT/'gallery_deployment_before.json')
    for name,h in old['frozen'].items():assert digest(PROJECT/name)==h,name
    for name,previous in old['services'].items():
        current=read(PROJECT/'outputs'/name/'supervisor.json');assert current['pid']==previous['pid'] and current['tunnel']['pid']==previous['tunnel']['pid']
        if name=='pallet_structure_review_managed_v1':assert current['app']['pid']==previous['app']['pid']
    stores={}
    for label,table,snapshot,live in (('pose','annotations',ROOT/'reviews_snapshot.sqlite3',PROJECT/'outputs/pallet_pose_human_review_v1/annotations.sqlite3'),
            ('gallery','reviews',ROOT/'gallery_reviews_snapshot.sqlite3',PROJECT/'outputs/pallet_mask_gallery_reviews_v1/mask_reviews.sqlite3')):
        with closing(sqlite3.connect(snapshot.as_uri()+'?mode=ro&immutable=1',uri=True)) as db:
            frozen={k:json.loads(raw) for k,raw in db.execute(f'SELECT target_key,payload FROM {table}')};events=list(db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'))
        with closing(sqlite3.connect(live.as_uri()+'?mode=ro',uri=True)) as db:
            assert db.execute('PRAGMA quick_check').fetchone()[0]=='ok';latest={k:json.loads(raw) for k,raw in db.execute(f'SELECT target_key,payload FROM {table}')}
            current_events=list(db.execute('SELECT id,target_key,revision,payload FROM events ORDER BY id'))
        assert all(saved_revision_preserved(v,latest.get(k)) for k,v in frozen.items()) and event_prefix_preserved(events,current_events)
        stores[label]=dict(frozen_saved=len(frozen),current_saved=len(latest),frozen_events=len(events),current_events=len(current_events),all_event_bytes_preserved=True)
    value=dict(state='passed',protected_formal_files=20768,fixed_denominator=12344,old_publication_files_preserved=len(old['frozen']),
        all_supervisors_and_tunnels_preserved=True,unrelated_configurations_preserved=True,human_stores=stores,
        production_annotation_writes=0,verified_at=datetime.now(timezone.utc).isoformat())
    result.write_bytes(canonical(value)+b'\n');print(json.dumps(value),flush=True)


if __name__=='__main__':
    import argparse
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--stage',choices=('sidecar','sources'),required=True)
    parser.add_argument('--gallery',type=Path,default=ROOT);parser.add_argument('--tasks',type=Path,default=TASKS)
    parser.add_argument('--output',type=Path,default=OUT);parser.add_argument('--version',type=int,default=VERSION)
    args=parser.parse_args();ROOT,TASKS,OUT=(p.resolve() for p in (args.gallery,args.tasks,args.output));VERSION=args.version
    if not all(p.is_relative_to(PROJECT/'outputs') for p in (ROOT,TASKS,OUT)):raise ValueError('Explicit output paths required')
    sidecar() if args.stage=='sidecar' else sources()
