"""Publication-8 provenance, four-vertex honesty, exhaustive audit and seal tests."""
import ast
import copy
import hashlib
import json
import sqlite3

import pytest

from scripts import verify_mask_quota_100_continue as audit


POLYGON = [[1, 1], [20, 1], [20, 10], [15, 10], [15, 5], [5, 5], [5, 10], [1, 10]]
FOUR = [[2, 2], [19, 1], [18, 9], [1, 10]]


def row(key='human', cls=9):
    return dict(target_key=key, target_id=key+'::box:0000', frame_id='frame-'+key,
        final_class_id=cls, split='train', policy_id='camera', viewpoint_candidate='front',
        group_id='group', box_index=0, bbox=dict(x=1, y=1, width=19, height=9),
        size=[24, 16], source_pcd_sha256='pcd')


def store(current, events=()):
    return dict(path=audit.Path('readonly.sqlite3'), metadata={}, current=current,
        events=list(events), history_keys={e[1] for e in events})


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(audit.canonical(value)+b'\n')


def write_jsonl(path, values):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(b''.join(audit.canonical(v)+b'\n' for v in values))


@pytest.fixture
def manual_fixture():
    r = row()
    human = dict(target_key='human', source=r, polygon=copy.deepcopy(FOUR), revision=6,
        state='draft', **dict.fromkeys(audit.FALSE_FLAGS, False))
    current = dict(human, revision=7, event_kind='axes_normalization')
    pose = store({'human': current}, [(10, 'human', 6, json.dumps(human, indent=2)),
        (11, 'human', 7, json.dumps(current))])
    direct = audit.independent_human_sources(pose, {'human': r}, allow_four=True)
    t = dict(direct['human'], origin=audit.POSE_ORIGIN,
        pose_review=audit.v1.pose_provenance(direct['human'], 'snapshot'))
    request = dict(target_key='human', class_id=9, source=dict(r, formal_manifest_sha256='formal'),
        pose_annotation_url='https://example.test/?target=human')
    p = dict(target_key='human', class_id=9, source=r, polygon=copy.deepcopy(FOUR), vertex_count=4,
        schema='saved_pose_mask_gallery_entry_v1', origin=audit.POSE_ORIGIN,
        human_edited=True, status='human_edited_draft_pending_confirmation',
        source_label_kind='human_mask_source_manual_template_draft', manual_source_kind='completed_manual_request',
        **dict.fromkeys(audit.FALSE_FLAGS, False), pose_snapshot_saved=True, pose_store_written=False,
        gallery_store_written=False, machine_transfer_performed=False, new_human_edit_created=False,
        manual_four_point_source=True, propagation_seed_eligible=False,
        manual_request_sha256=audit.sha(request), original_pose_url=request['pose_annotation_url'],
        rendering_id=audit.NAMESPACE+':human', snapshot_sha256='snapshot', target_expected_revision=7,
        target_snapshot_payload_sha256=audit.sha(current), formal_manifest_sha256='formal', class_assignments_sha256='classes',
        template=audit.template_binding(t), metrics={}, flags=['manual_source_not_machine_transfer'])
    return p, request, pose, direct, r, 'snapshot', 'formal', 'classes'


def test_real_four_vertex_human_counts_without_inventing_vertices_or_seeding(manual_fixture):
    audit.check_manual(*manual_fixture)
    p, _, pose, _, r, *_ = manual_fixture
    assert p['polygon'] == FOUR and p['vertex_count'] == p['template']['vertex_count'] == 4
    assert p['template']['human_polygon_revision'] == 6
    assert audit.independent_human_sources(pose, {'human': r}) == {}
    assert audit.independent_seed_union(pose, {}, {'human': r}, 'snapshot', {}, {}) == ({}, {})


def test_manual_four_can_use_explicit_non_template_human_source_binding(manual_fixture):
    p = manual_fixture[0]
    p['human_source'] = p.pop('template')
    p['rendering_id'] = audit.NAMESPACE+':manual_source:human'
    audit.check_manual(*manual_fixture)
    assert 'template' not in p


@pytest.mark.parametrize('attack', ['invent_vertex', 'vertex_count', 'rectangle', 'class', 'split', 'pcd',
    'event_hash', 'current_hash', 'snapshot', 'revision', 'request_hash', 'request_url', 'self_source', 'namespace',
    'confirmation', 'GT', 'training', 'robot', 'human', 'source_confirmation', 'source_gt', 'transfer', 'new_edit',
    'write', 'metrics', 'continuation', 'deleted', 'deferred', 'source_kind'])
def test_manual_four_cannot_be_stale_synthetic_or_confirmed(manual_fixture, attack):
    p, request, pose, direct, r, *_ = manual_fixture
    if attack == 'invent_vertex':
        p['polygon'].insert(1, [10, 1])
        p['vertex_count'] = 5
    elif attack == 'vertex_count':
        p['vertex_count'] = 12
    elif attack == 'rectangle':
        rectangle = [[1, 1], [20, 1], [20, 10], [1, 10]]
        p['polygon'] = pose['current']['human']['polygon'] = direct['human']['polygon'] = rectangle
    elif attack == 'class':
        p['class_id'] = 1
    elif attack == 'split':
        request['source']['split'] = 'test'
    elif attack == 'pcd':
        p['source'] = dict(r, source_pcd_sha256='other')
    elif attack == 'event_hash':
        p['template']['human_event_sha256'] = audit.sha(json.loads(pose['events'][0][3]))
    elif attack == 'current_hash':
        p['target_snapshot_payload_sha256'] = 'stale'
    elif attack == 'snapshot':
        p['snapshot_sha256'] = 'old'
    elif attack == 'revision':
        p['target_expected_revision'] = 6
    elif attack == 'request_hash':
        p['manual_request_sha256'] = 'fake'
    elif attack == 'request_url':
        p['original_pose_url'] = 'https://example.test/?target=another'
    elif attack == 'self_source':
        p['template']['target_key'] = 'another'
    elif attack == 'namespace':
        p['rendering_id'] = 'quota100_generation:human'
    elif attack in ('confirmation', 'GT', 'training', 'robot'):
        p[dict(confirmation='human_mask_confirmed', GT='ground_truth_eligible',
            training='automatic_training_eligible', robot='robot_command_eligible')[attack]] = True
    elif attack == 'human':
        p['human_edited'] = False
    elif attack in ('source_confirmation', 'source_gt'):
        pose['current']['human']['human_mask_confirmed' if attack == 'source_confirmation' else 'ground_truth_eligible'] = True
    elif attack in ('transfer', 'new_edit', 'write'):
        p[dict(transfer='machine_transfer_performed', new_edit='new_human_edit_created', write='gallery_store_written')[attack]] = True
    elif attack == 'metrics':
        p['metrics'] = {'ecc': 1.0}
    elif attack == 'continuation':
        p['continuation'] = {'batch': 8}
    elif attack in ('deleted', 'deferred'):
        pose['current']['human']['state'] = attack
    else:
        p['manual_source_kind'] = 'machine'
    with pytest.raises(ValueError):
        audit.check_manual(*manual_fixture)


@pytest.mark.parametrize('polygon', [FOUR, POLYGON])
def test_actual_human_after_machine_is_required_even_when_polygons_equal(polygon):
    r = row()
    human = dict(target_key='human', revision=1, state='draft', source=r, polygon=polygon)
    machine = dict(human, revision=2, event_kind='mask_template_proposal')
    pose = store({'human': machine}, [(1, 'human', 1, json.dumps(human)), (2, 'human', 2, json.dumps(machine))])
    assert audit.independent_human_sources(pose, {'human': r}, allow_four=True) == {}
    later_human = dict(human, revision=3)
    pose['events'].append((3, 'human', 3, json.dumps(later_human)))
    pose['current']['human'] = later_human
    assert audit.independent_human_sources(pose, {'human': r}, allow_four=True)['human']['human_polygon_revision'] == 3


def test_machine_only_old_human_and_default_rectangles_are_not_manual_sources():
    r = row()
    for kind, polygon in [('mask_template_proposal', FOUR), (None, [[1, 1], [20, 1], [20, 10], [1, 10]])]:
        value = dict(target_key='human', revision=1, state='draft', source=r, polygon=polygon, event_kind=kind)
        pose = store({'human': value}, [(1, 'human', 1, json.dumps(value))])
        assert audit.independent_human_sources(pose, {'human': r}, allow_four=True) == {}


def candidate(key, cls=1, frame=None, group='group', quality=.9):
    r = row(key, cls)
    r['group_id'] = group
    if frame is not None:
        r['frame_id'] = frame
    return dict(target_key=key, class_id=cls, source=r, polygon=POLYGON,
        metrics=dict(boundary_ncc=quality, ecc=.95))


def quota_fixture():
    old, old_manual, gallery = {}, {}, {'current': {}}
    # 378 parent proposals, of which 203 have actual latest gallery revisions.
    gallery_counts = {1: 30, 2: 90, 9: 50, 10: 27, 15: 6}
    manual_counts = {1: 7, 2: 10, 9: 11, 10: 27, 15: 32}
    for cls, count in {1: 58, 2: 100, 9: 83, 10: 54, 15: 83}.items():
        for i in range(count):
            key = f'{cls}-{i}'
            old[key] = candidate(key, cls)
            if i < gallery_counts[cls]:
                gallery['current'][key] = dict(polygon=POLYGON)
            elif i < gallery_counts[cls]+manual_counts[cls]:
                old_manual[key] = old[key]
    manual = {}
    for cls, count in {1: 10, 9: 2, 10: 10, 15: 2}.items():
        for i in range(count):
            key = f'new-{cls}-{i}'
            manual[key] = candidate(key, cls)
    manual['new-9-0']['polygon'] = FOUR
    return old, old_manual, manual, gallery


def test_requested_base_402_counts_real_four_and_not_45_unsaved_or_43_old_pending():
    old, old_manual, manual, gallery = quota_fixture()
    classes, counts = audit.expected_counts(old, old_manual, manual, {}, gallery, set(manual))
    assert len(old) == 378 and len(old_manual) == 87 and len(manual) == 24
    assert {c: v['distinct_frames'] for c, v in counts.items()} == {'1': 68, '2': 100, '9': 85, '10': 64, '15': 85}
    assert sum(v['saved_human'] for v in classes.values()) == 314
    assert sum(v['saved_fine_edits'] for v in classes.values()) == 313
    assert sum(v['prior_machine_pending'] for v in classes.values()) == 88
    assert sum(v['saved_gallery_human'] for v in classes.values()) == 203
    assert sum(v['saved_pose_human'] for v in classes.values()) == 111
    assert sum(v['new_machine_pending'] for v in classes.values()) == 0


def test_cap_100_and_diversity_consume_every_human_and_historical_frame():
    base = {str(i): candidate(str(i)) for i in range(100)}
    assert audit.count_frames(list(base.values()))['1']['shortfall'] == 0
    accepted = {'fresh': candidate('fresh'), 'dup': candidate('dup', frame='frame-0')}
    outcomes = dict(fresh=dict(reason='accepted_quota_full_not_selected'), dup=dict(reason='accepted_duplicate_frame_not_selected'))
    audit.check_diversity(base, accepted, {}, outcomes)
    with pytest.raises(ValueError, match='exceeds 100'):
        audit.count_frames(list(base.values())+[candidate('extra')])
    with pytest.raises(ValueError, match='Repeated frame'):
        audit.count_frames([candidate('one'), candidate('two', frame='frame-one')])


def test_reuse_is_independently_derived_and_skips_full_class_two_quota():
    rows, current, events = {}, {}, []
    for i, (key, cls) in enumerate((('genuine', 1), ('full', 2), ('machine', 1), ('confirmed', 1)), 1):
        r = rows[key] = row(key, cls)
        v = dict(target_key=key, source=r, revision=1, state='draft', polygon=POLYGON,
            **dict.fromkeys(audit.FALSE_FLAGS, False))
        if key == 'machine':
            v['event_kind'] = 'mask_template_proposal'
        if key == 'confirmed':
            v['human_mask_confirmed'] = True
        current[key] = v
        events.append((i, key, 1, json.dumps(v)))
    pose = store(current, events)
    direct = audit.independent_human_sources(pose, rows)
    old = {str(i): candidate(str(i), 2) for i in range(100)}
    selected, inventory = audit.independent_reuse(pose, direct, rows, old, {})
    assert selected == {'genuine'}
    assert inventory['full']['reason'] == 'quota_full'
    assert inventory['confirmed']['reason'] == 'confirmed_or_eligible'
    assert 'machine' not in inventory


def test_seed_union_never_uses_unsaved_parent_and_latest_gallery_wins(manual_fixture):
    _, _, pose, _, r, *_ = manual_fixture
    gallery = dict(row=r, polygon=POLYGON, origin=audit.GALLERY_ORIGIN)
    assert audit.independent_seed_union(pose, {'human': gallery}, {'human': r}, 'snapshot', {}, {})[1] == {'human': gallery}
    v = dict(pose['current']['human'], polygon=POLYGON, revision=8)
    pose['current']['human'] = v
    v.pop('event_kind')
    pose['events'].append((12, 'human', 8, json.dumps(v)))
    with pytest.raises(ValueError, match='Unreviewed historical machine'):
        audit.independent_seed_union(pose, {}, {'human': r}, 'snapshot', {'human': {}}, {})


@pytest.mark.parametrize('version', [3, 4, 5, 6, 7])
@pytest.mark.parametrize('attack', [None, 'binding', 'image', 'proposal', 'source'])
def test_latest_gallery_binding_uses_its_actual_historical_publication(tmp_path, monkeypatch, version, attack):
    from pallet.mask_gallery_review import VERSION as editor_version
    key, r = 'gallery', row('gallery')
    pub, parent = tmp_path/'historical', tmp_path/'parent'
    for root in (pub, parent):
        (root/'images').mkdir(parents=True)
        (root/'images'/f'{key}.png').write_bytes(b'original native image')
    (pub/'proposals.jsonl').write_text('frozen proposal bytes')
    proposal = dict(source=r, polygon=POLYGON, template={'old': 'source'})
    source = {f: r[f] for f in ('target_key', 'frame_id', 'split', 'box_index', 'bbox', 'size', 'source_pcd_sha256')}
    source.update(formal_manifest_sha256='formal', image_sha256=audit.digest(pub/'images'/f'{key}.png'))
    value = dict(target_key=key, revision=2, proposal_publication=version, base_proposal_id=audit.sha(proposal),
        proposal_polygon=POLYGON, template_provenance=proposal['template'], source=source, source_binding=audit.sha(source),
        binding=audit.sha(dict(formal='formal', proposals=audit.digest(pub/'proposals.jsonl'), editor_version=editor_version)),
        event_kind='human_mask_gallery_revision', human_edited=True, polygon=POLYGON, vertex_count=8, pose=None,
        **dict.fromkeys(audit.FALSE_FLAGS, False), pose_store_written=False, original_proposal_modified=False)
    monkeypatch.setattr(audit, 'PARENT', parent)
    args = (store({}), store({key: value}), {key: r}, {key: proposal}, 'formal', 'gallery-snapshot',
        {version: dict(path=pub, proposals={key: proposal})})
    if attack == 'binding':
        value['binding'] = 'latest-not-source-publication'
    elif attack == 'image':
        (parent/'images'/f'{key}.png').write_bytes(b'changed pixels')
    elif attack == 'proposal':
        value['base_proposal_id'] = 'another proposal hash'
    elif attack == 'source':
        value['source'] = dict(source, frame_id='another image')
    if attack:
        with pytest.raises(ValueError):
            audit.independent_gallery_templates(*args)
    else:
        assert audit.independent_gallery_templates(*args)[key]['gallery_review']['proposal_publication'] == version


class Evidence:
    def patch(self, key):
        return key

    def image(self, frame):
        return frame


@pytest.fixture
def attempt_fixture(tmp_path, monkeypatch):
    r = row('target', 2)
    t = dict(row=row('seed', 2), polygon=POLYGON)
    trial = dict(target_key='target', class_id=2, template_key='seed', metrics=dict(rejection='affine_registration_failed'))
    write_jsonl(tmp_path/'registration_attempts.jsonl', [trial])
    write_jsonl(tmp_path/'new_proposals.jsonl', [])
    monkeypatch.setattr(audit, 'correlate', lambda *_: .9)
    monkeypatch.setattr(audit, 'transfer', lambda *_: (None, copy.deepcopy(trial['metrics'])))
    args = (tmp_path, {'target': r}, {'target': 'eligible'}, {'history_keys': set()}, {}, {},
        {'seed': t}, {}, {'target': dict(reason='registration_or_boundary_rejected')}, Evidence())
    return args, trial


def test_every_rejected_attempt_is_recomputed_and_missing_attempts_detected(attempt_fixture, monkeypatch):
    args, _ = attempt_fixture
    assert audit.audit_attempts(*args) == ({'target'}, 1)
    monkeypatch.setattr(audit, 'transfer', lambda *_: (None, dict(rejection='different')))
    with pytest.raises(ValueError, match='value differs'):
        audit.audit_attempts(*args)
    args[6]['second'] = dict(row=row('second', 2), polygon=POLYGON)
    with pytest.raises(ValueError, match='coverage/order'):
        audit.audit_attempts(*args)


def test_falsely_rejected_success_cannot_hide_from_audit(attempt_fixture, monkeypatch):
    args, _ = attempt_fixture
    monkeypatch.setattr(audit, 'transfer', lambda *_: (POLYGON, {}))
    monkeypatch.setattr(audit, 'affine_reference', lambda *_: None)
    monkeypatch.setattr(audit, 'beam_boundary_audit', lambda *_: {'state': 'passed'})
    with pytest.raises(ValueError, match='falsely rejected'):
        audit.audit_attempts(*args)


def test_batch_eight_rank_and_unselected_acceptance_still_audited(attempt_fixture):
    args, trial = attempt_fixture
    args[7]['target'] = dict(template={'target_key': 'seed'}, metrics=trial['metrics'], continuation=dict(
        batch=8, template_rank=1, all_compatible_targets_scanned=True, recursive_candidate_propagation=False))
    args[-2]['target']['reason'] = 'accepted_quota_full_not_selected'
    assert audit.audit_attempts(*args) == ({'target'}, 1)
    args[7]['target']['continuation']['batch'] = 7
    with pytest.raises(ValueError, match='continuation/rank'):
        audit.audit_attempts(*args)


def test_actual_four_source_freeze_checks_raw_sqlite_bytes(tmp_path, manual_fixture):
    p, _, pose, *_ = manual_fixture
    snapshot = tmp_path/'snapshot.sqlite3'
    raw = json.dumps(pose['current']['human'], indent=1)
    event_id, key, event_revision, event_raw = pose['events'][0]
    with sqlite3.connect(snapshot) as db:
        db.executescript('CREATE TABLE annotations(target_key TEXT,revision INTEGER,payload TEXT);'
            'CREATE TABLE events(id INTEGER,target_key TEXT,revision INTEGER,payload TEXT);')
        db.execute('INSERT INTO annotations VALUES (?,?,?)', (key, 7, raw))
        db.execute('INSERT INTO events VALUES (?,?,?,?)', (event_id, key, event_revision, event_raw))
    record = dict(schema='saved_pose_mask_source_freeze_v1', target_key=key, snapshot_sha256='snapshot',
        current_revision=7, current_payload_sha256=audit.sha(json.loads(raw)), current_payload_raw=raw,
        current_payload=json.loads(raw), current_payload_raw_sha256=hashlib.sha256(raw.encode()).hexdigest(),
        human_event_id=event_id, human_polygon_revision=event_revision, human_event_sha256=hashlib.sha256(event_raw.encode()).hexdigest(),
        human_event_payload_raw=event_raw, human_event_payload=json.loads(event_raw), polygon_sha256=audit.sha(p['polygon']),
        vertex_count=4, manual_four_point_source=True, propagation_seed_eligible=False)
    before = snapshot.read_bytes()
    audit.check_new_manual_records({key: record}, {key: p}, snapshot, 'snapshot')
    assert snapshot.read_bytes() == before
    record['human_event_payload_raw'] += ' '
    with pytest.raises(ValueError, match='exact raw SQLite payload/event'):
        audit.check_new_manual_records({key: record}, {key: p}, snapshot, 'snapshot')


def test_parent_partition_inherits_87_not_only_57_and_machine_sidecar_is_exclusive():
    old, old_manual, manual, _ = quota_fixture()
    new = {'machine': candidate('machine')}
    combined = {**old, **manual, **new}
    audit.previous.check_partition(old, old_manual, manual, new, combined, new, {**old_manual, **manual})
    with pytest.raises(ValueError, match='treated as accepted transfer'):
        audit.previous.check_partition(old, old_manual, manual, new, combined, {**manual, **new}, {**old_manual, **manual})
    combined[next(iter(old))] = {'changed': True}
    with pytest.raises(ValueError, match='canonical object'):
        audit.previous.check_partition(old, old_manual, manual, new, combined, new, {**old_manual, **manual})


@pytest.fixture
def inherited_fixture(tmp_path, monkeypatch):
    manual, historical, current, direct, audits, overlays = {}, {}, {}, {}, {}, {}
    for i in range(87):
        key, r = f'old-human-{i}', row(f'old-human-{i}')
        value = dict(target_key=key, source=r, polygon=POLYGON, revision=5, state='draft',
            **dict.fromkeys(audit.FALSE_FLAGS, False))
        p = dict(target_key=key, polygon=POLYGON, snapshot_sha256='original-snapshot',
            target_expected_revision=4, target_snapshot_payload_sha256='historical-current',
            template=dict(human_event_sha256='historical-event'), **dict.fromkeys(audit.FALSE_FLAGS, False))
        manual[key], current[key] = p, value
        direct[key] = dict(row=r, polygon=POLYGON)
        historical[key] = dict(target_key=key, current_payload={'polygon': POLYGON}, snapshot_sha256='original-snapshot',
            current_payload_sha256='historical-current', human_event_sha256='historical-event')
        expected = dict(target_key=key, original_proposal_sha256=audit.sha(p), historical_revision=4,
            current_revision=5, current_payload_sha256=audit.sha(value), latest_active_direct_human=True,
            source_changed=True, polygon_changed=False, historical_assets_preserved=True)
        audits[key] = expected
        overlays[key] = dict(target_key=key, snapshot_sha256='new-snapshot', inherited_manual_source=True, legacy_source_audit=expected)
    def read(path):
        if path.name == 'inherited_manual_source_audit.jsonl':
            return list(audits.values())
        if path.name == 'all_manual_sources.jsonl':
            return list(historical.values())
        values = list(historical.values())
        return values[:57] if path.parent == audit.PARENT else values[57:]
    monkeypatch.setattr(audit, 'read_jsonl', read)
    calls = []
    monkeypatch.setattr(audit, 'check_new_manual_records', lambda *args: calls.append(args))
    return (tmp_path, manual, tmp_path/'snapshot.sqlite3', store(current), direct, 'new-snapshot', overlays), calls, audits


def test_all_87_inherited_manual_objects_keep_original_binding_and_separate_current_raw_audit(inherited_fixture):
    args, calls, _ = inherited_fixture
    before = copy.deepcopy(args[1])
    records, changed = audit.check_inherited_manual(*args)
    assert len(records) == len(changed) == 87
    assert args[1] == before and all(p['snapshot_sha256'] == 'original-snapshot' for p in args[1].values())
    assert calls[0][3] == 'new-snapshot'


@pytest.mark.parametrize('attack', ['only_57', 'no_current', 'stale_current', 'silent_change', 'no_overlay', 'rewrite_canonical'])
def test_inherited_current_audits_cannot_omit_30_or_rebind_original_87(inherited_fixture, attack):
    args, _, audits = inherited_fixture
    _, manual, _, pose, direct, _, overlays = args
    key = next(iter(manual))
    if attack == 'only_57':
        for k in list(audits)[57:]:
            del audits[k]
    elif attack == 'no_current':
        del direct[key]
    elif attack == 'stale_current':
        pose['current'][key]['revision'] += 1
    elif attack == 'silent_change':
        audits[key]['source_changed'] = False
    elif attack == 'no_overlay':
        overlays[key]['inherited_manual_source'] = False
    else:
        manual[key]['snapshot_sha256'] = 'new-snapshot'
    with pytest.raises(ValueError):
        audit.check_inherited_manual(*args)


def test_render_inventory_excludes_manual_four_but_preserves_binding_and_all_old_namespaces(tmp_path):
    t = dict(row=row('seed'), polygon=POLYGON, origin=audit.POSE_ORIGIN)
    historical = [dict(t, rendering_id=ns+':seed', polygon=[[1, 1]])
        for ns in ('historical', 'refined', 'generation', 'quota_generation', 'quota100_generation')]
    parent = dict(templates=historical, rendering_by_target={'old': 'quota100_generation:seed'})
    inventory = dict(templates=copy.deepcopy(historical)+[dict(t, rendering_id=audit.NAMESPACE+':seed')],
        rendering_by_target={'old': 'quota100_generation:seed', 'four': audit.NAMESPACE+':four'},
        historical_templates=5, generation_template_namespace=audit.NAMESPACE, generation_template_keys=['seed'],
        generation_templates=1, generation_templates_by_origin={audit.POSE_ORIGIN: 1}, deferred_manual_template_keys=['four'],
        manual_source_renderings=[dict(target_key='four', rendering_id=audit.NAMESPACE+':four', polygon=FOUR,
            human_source={'target_key': 'four'}, manual_four_point_source=True, propagation_seed_eligible=False)])
    write_json(tmp_path/audit.NAMESPACE/'templates/seed.json', t)
    args = (tmp_path, inventory, parent, {'seed': t}, {'old': {}},
        {'four': dict(template={'target_key': 'four'}, polygon=FOUR, manual_four_point_source=True,
            rendering_id=audit.NAMESPACE+':four')}, {})
    audit.check_rendering(*args)
    inventory['templates'].append(dict(t, rendering_id=audit.NAMESPACE+':four', polygon=FOUR))
    with pytest.raises(ValueError, match='namespace coverage'):
        audit.check_rendering(*args)


def test_frozen_hashes_are_real_and_verifier_never_imports_new_generator():
    for name, expected in audit.PARENT_PINS.items():
        assert audit.digest(audit.PARENT/name) == expected
    for name, expected in audit.REQUEST_PINS.items():
        assert audit.digest(audit.REQUESTS/name) == expected
    for name, expected in audit.ORIGINAL_CODE.items():
        assert audit.digest(audit.PROJECT/name) == expected
    tree = ast.parse(audit.Path(audit.__file__).read_text())
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom):
            assert node.module != 'pallet.mask_quota_100_continue'
        elif isinstance(node, ast.Import):
            assert all(alias.name != 'pallet.mask_quota_100_continue' for alias in node.names)
    assert len(audit.REQUEST_KEYS) == 24
    assert audit.digest(audit.PROJECT/audit.GENERATOR) == audit.GENERATOR_SHA


def test_failed_audit_never_creates_success_seal(tmp_path, monkeypatch):
    out = tmp_path/'candidate'
    out.mkdir()
    write_json(out/'manifest.json', {})
    monkeypatch.setattr(audit, 'OUTPUT', out)
    def fail(*_):
        raise ValueError('unverified human source')
    monkeypatch.setattr(audit, 'audit', fail)
    with pytest.raises(ValueError, match='unverified human source'):
        audit.main(['--output', str(out)])
    assert not (out/'verification.json').exists()
    assert audit.read_json(out/'validation_report.json')['state'] == 'failed'


def test_success_seal_has_pub8_gallery_contract_and_cannot_be_overwritten(tmp_path, monkeypatch):
    out = tmp_path/'candidate'
    out.mkdir()
    write_json(out/'manifest.json', {})
    monkeypatch.setattr(audit, 'OUTPUT', out)
    monkeypatch.setattr(audit, 'audit', lambda *_: dict(state='passed', publication_version=8, proposals_verified=409,
        proposals_sha256='sealed', extra_public_images=['vertex2_before_after.png']))
    audit.main(['--output', str(out)])
    seal = audit.read_json(out/'verification.json')
    assert seal['publication_version'] == 8 and seal['proposals_verified'] == 409
    assert seal['extra_public_images'] == ['vertex2_before_after.png']
    assert seal['validation_report_sha256'] == audit.digest(out/'validation_report.json')
    before = (out/'verification.json').read_bytes()
    with pytest.raises(ValueError, match='overwrite a frozen verification'):
        audit.main(['--output', str(out)])
    assert (out/'verification.json').read_bytes() == before


def test_symlink_output_cannot_rewrite_frozen_parent_report(tmp_path, monkeypatch):
    parent, link = tmp_path/'parent', tmp_path/'candidate'
    parent.mkdir()
    write_json(parent/'manifest.json', {})
    (parent/'validation_report.json').write_text('immutable')
    link.symlink_to(parent, target_is_directory=True)
    monkeypatch.setattr(audit, 'OUTPUT', link)
    with pytest.raises(ValueError, match='publication-8'):
        audit.main(['--output', str(link)])
    assert (parent/'validation_report.json').read_text() == 'immutable'
