"""TVGG R01 companion, 2026-10-01. Python 3, standard library only.

Run: python3 output-contract-example.py

All six example records below are synthetic. They demonstrate the retrospective
six-field rule described in R01, not factual accuracy or the historical batch.
No network requests, model calls, credentials or private records are required.
Expected: 6 records, 5 success flags, 3 direct targets, 2 nested-only targets,
1 literal contract pass and 1 saved error. Nested candidates are not normalized.
"""
import json

TARGET = 'runs_door_to_door_or_canvassing_teams'
LOCAL = 'local_to_birmingham_alabama'
DIRECTORY = 'is_directory_or_aggregator_not_a_real_company'
STRINGS = ('company_name', 'what_they_sell', 'evidence')
FIELDS = {*STRINGS, TARGET, LOCAL, DIRECTORY}


def valid_contract(payload):
    return (isinstance(payload, dict) and set(payload) == FIELDS
            and all(isinstance(payload.get(key), str) for key in STRINGS)
            and payload.get(LOCAL) in ('yes', 'no', 'unclear')
            and payload.get(TARGET) in ('yes', 'no', 'unclear')
            and isinstance(payload.get(DIRECTORY), bool))


def contains_target(value):
    if isinstance(value, dict):
        return TARGET in value or any(contains_target(v) for v in value.values())
    if isinstance(value, list):
        return any(contains_target(v) for v in value)
    return False


base = {'company_name': 'Synthetic example', 'what_they_sell': 'Example services',
        'evidence': 'Invented fixture, not factual evidence.', LOCAL: 'unclear',
        TARGET: 'unclear', DIRECTORY: False}
records = [
    {'id': 'direct-valid', 'ok': True, 'llm': base},
    {'id': 'nested-object', 'ok': True, 'llm': {'content': base}},
    {'id': 'nested-list', 'ok': True, 'llm': {'content': [base]}},
    {'id': 'invalid-category', 'ok': True, 'llm': {**base, TARGET: 'YES'}},
    {'id': 'wrong-type', 'ok': True, 'llm': {**base, DIRECTORY: 'false'}},
    {'id': 'saved-error', 'ok': False, 'llm': None},
]
successful = [r for r in records if r['ok'] is True]
result = {
    'synthetic_records': len(records),
    'success_flags': len(successful),
    'direct_target': sum(isinstance(r['llm'], dict) and TARGET in r['llm'] for r in successful),
    'nested_only_target': sum(isinstance(r['llm'], dict) and TARGET not in r['llm'] and contains_target(r['llm']) for r in successful),
    'literal_contract_passes': sum(valid_contract(r['llm']) for r in successful),
    'saved_errors': sum(r['ok'] is False for r in records),
}
expected = dict(zip(result, (6, 5, 3, 2, 1, 1)))
assert result == expected, (result, expected)
print(json.dumps(result, indent=2))
print('Synthetic demonstration passed. No factual classifications were evaluated.')
