"""Deterministic, synthetic counterexamples for the 2026-11-10 addenda.

Python 3 standard library only. No manuscript data or external experiments.
Run: python3 illustrative_checks.py --output DIRECTORY
"""
import argparse
import csv
import hashlib
import json
from fractions import Fraction as F
from pathlib import Path

DATE = '2026-11-10'


def calculate():
    cases = {}
    # Binary labels are assigned, not produced by an LLM or an empirical judge.
    before = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
    after =  [0, 0, 0, 1, 1, 1, 1, 1, 0, 0]
    clean_before = [0] * 10
    clean_after = [0] * 9 + [1]
    prevented = sum(a == 1 and b == 0 for a, b in zip(before, after))
    introduced = sum(a == 0 and b == 1 for a, b in zip(before, after))
    persistent = sum(a == b == 1 for a, b in zip(before, after))
    assert (prevented, introduced, persistent) == (3, 2, 3)
    assert sum(before) - sum(after) == prevented - introduced == 1
    cases['rag-knowledge-base-poisoning-liability'] = {
        'kind': 'synthetic assigned binary transitions; no model execution',
        'inputs': {'clean_undefended': clean_before, 'clean_defended': clean_after,
                   'poisoned_undefended': before, 'poisoned_defended': after},
        'results': {'queries': 10, 'before_positive': 6, 'after_positive': 5,
                    'prevented': prevented, 'introduced': introduced,
                    'persistent': persistent, 'net_reduction': 1,
                    'clean_introduced': sum(clean_after)},
        'rows': [['合成質問数', '10件'], ['汚染下の標的回答', '6件 → 5件'],
                 ['抑止／新規／持続', '3件／2件／3件'],
                 ['純減／正常条件での新規', '1件／1件']],
        'limit': '各ラベルは任意に与えた値です。防御の性能、発生確率や損害を推定していません。'
    }

    energy = [F(2), F(18)]
    mass = [F(1), F(3)]
    aggregate = sum(energy) / sum(mass)
    naive = sum(e / m for e, m in zip(energy, mass)) / len(mass)
    assert aggregate == 5 and naive == 4
    assert sum((m / sum(mass)) * (e / m) for e, m in zip(energy, mass)) == aggregate
    cases['chemical-process-boundaries'] = {
        'kind': 'synthetic interval totals; no electrolysis or membrane measurements',
        'inputs': {'energy_kWh': [2, 18], 'conforming_mass_kg': [1, 3]},
        'results': {'aggregate_kWh_per_kg': float(aggregate),
                    'unweighted_mean_kWh_per_kg': float(naive)},
        'rows': [['区間別の購入電力', '2、18 kWh'], ['区間別の適合量', '1、3 kg'],
                 ['積算比', '20 / 4 = 5 kWh/kg'],
                 ['区間比の単純平均', '(2 / 1 + 18 / 3) / 2 = 4 kWh/kg']],
        'limit': '工程量を模した任意値です。CO₂電解の実測値や既存系列の再計算値ではありません。'
    }

    def effects(keys):
        # Each ledger update and effect is atomic. No expiry or concurrency.
        ledger = set()
        count = 0
        for caller, key in keys:
            if (caller, key) not in ledger:
                count += 1
                ledger.add((caller, key))
        return count

    same = effects([('caller', 'intent-A'), ('caller', 'intent-A')])
    new = effects([('caller', 'intent-A'), ('caller', 'retry-new-key')])
    independent = effects([('caller', 'intent-A'), ('caller', 'intent-B')])
    assert (same, new, independent) == (1, 2, 2)
    cases['cloud-outages-response-duties'] = {
        'kind': 'synthetic ledger state transitions; no API or fault-injection run',
        'inputs': {'attempts_per_case': 2, 'first_effect_committed': True,
                   'first_response_lost': True, 'atomic_ledger_and_effect': True,
                   'no_expiry_or_concurrency': True},
        'results': {'same_intent_same_key_effects': same,
                    'same_intent_new_key_effects': new,
                    'independent_intents_effects': independent},
        'rows': [['各例の要求回数', '2回（初回確定後の応答消失を仮定）'],
                 ['同一意図・同一キー', '業務効果1件'],
                 ['同一意図・別キー', '業務効果2件'],
                 ['独立した二つの意図', '同じ内容でも業務効果2件']],
        'limit': '原子的な台帳と有効なキー保存を仮定します。同時実行、期限切れ、実障害は試験していません。'
    }

    # Seconds since 09:59:00, on a common perfect clock. Only two probes.
    ack, deadline, first, last = 30, 60, 0, 120
    possible_transitions = [45, 90]
    assert all(first < t <= last and ack < t for t in possible_transitions)
    outcomes = [t <= deadline for t in possible_transitions]
    assert outcomes == [True, False]
    cases['receipt-asynchronous-messaging'] = {
        'kind': 'two constructed compatible technical histories; no legal determination',
        'inputs': {'origin': '09:59:00', 'unit': 'seconds', 'ack_202': ack,
                   'deadline': deadline, 'unavailable_probe': first,
                   'available_probe': last, 'possible_transition_times': possible_transitions,
                   'single_transition_within_interval': True},
        'results': {'compatible_histories': 2, 'technical_availability_by_deadline': outcomes,
                    'deadline_is_inside_evidential_interval': first < deadline < last},
        'rows': [['両履歴で同じ202応答', '09:59:30'],
                 ['履歴A／Bの取得可能時刻', '09:59:45／10:00:30'],
                 ['仮の期限', '10:00:00（Aは前、Bは後）'],
                 ['2回の観測だけが支える区間', '(09:59:00, 10:01:00]']],
        'limit': '時計誤差なし・同一通知の仮定です。技術的取得可能性の例で、法的到達の判定ではありません。'
    }

    gross, reserved, ineligible, candidate = map(F, [10, 4, 2, 4])
    factor, demand = F(9, 10), F(4)
    assert gross == reserved + ineligible + candidate
    ceiling = candidate * factor
    shortfall = demand - ceiling
    assert ceiling == F(18, 5) and shortfall == F(2, 5)
    cases['tritium-supply-commitments'] = {
        'kind': 'synthetic disjoint inventory partition; no real stock estimate',
        'inputs': {'gross_kg': 10, 'allocated_elsewhere_kg': 4,
                   'ineligible_by_deadline_kg': 2, 'candidate_kg': 4,
                   'on_time_transfer_factor': 0.9, 'demand_kg': 4,
                   'decay_ignored': True},
        'results': {'transfer_ceiling_kg': float(ceiling), 'shortfall_kg': float(shortfall)},
        'rows': [['重複しない総量の内訳', '10 = 引当4 + 対象外2 + 候補4 kg'],
                 ['仮の期日内移送率', '90%（崩壊なし）'],
                 ['期日内移送上限', '4 × 0.9 = 3.6 kg'],
                 ['需要4 kgとの差', '0.4 kg不足']],
        'limit': '在庫・適格性・移送率はすべて仮定値です。供給予測や納入確約ではありません。'
    }

    duration = [F(1, 4), F(1), F(1, 4)]
    generation, auxiliary = [0, 200, 0], [100, 50, 100]
    net_energy = sum((g - a) * t for g, a, t in zip(generation, auxiliary, duration))
    mean = net_energy / sum(duration)
    assert net_energy == 100 and mean == F(200, 3)
    def closed(start, end):
        return start == end  # exact assumed states, not an empirical tolerance
    assert closed(50, 50) and not closed(50, 30)
    cases['tokamak-net-electricity'] = {
        'kind': 'synthetic three-phase energy accounting; no plant or UKAEA model run',
        'inputs': {'phase_duration_h': [float(t) for t in duration],
                   'generation_MWe': generation, 'auxiliary_MWe': auxiliary,
                   'closed_storage_example_MWh': [50, 50],
                   'unclosed_storage_example_MWh': [50, 30]},
        'results': {'flat_top_net_MWe': 150, 'cycle_net_MWh': float(net_energy),
                    'cycle_mean_MWe': float(mean),
                    'repeatability_gate_closed_example': True,
                    'repeatability_gate_unclosed_example': False},
        'rows': [['立上げ／平坦部／停止', '0.25／1／0.25 h'],
                 ['発電端／補機', '0, 200, 0／100, 50, 100 MWe'],
                 ['平坦部の正味出力', '150 MWe'],
                 ['全周期の正味電力量／平均', '100 MWh／66.7 MWe（小数1桁）'],
                 ['蓄積状態の確認例', '50 → 50 MWhは一致、50 → 30 MWhは不一致']],
        'limit': '全数値は仮定です。蓄積の一致は反復収支の必要な確認の一つで、十分条件ではありません。'
    }
    return {'date': DATE, 'status': 'synthetic illustrations only; no empirical validation',
            'arithmetic': 'exact rational arithmetic for interval totals and energy balance',
            'cases': cases}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=True)
    payload = calculate()
    payload['script_sha256'] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
    (args.output / 'illustrative-results.json').write_text(
        json.dumps(payload, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    with (args.output / 'illustrative-results.csv').open('w', encoding='utf-8-sig', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['date', 'paper_id', 'kind', 'metric', 'value_json'])
        for paper_id, case in payload['cases'].items():
            for metric, value in case['results'].items():
                writer.writerow([DATE, paper_id, case['kind'], metric, json.dumps(value)])
    print(json.dumps({'date': DATE, 'verified_illustrations': len(payload['cases']),
                      'output': str(args.output)}, ensure_ascii=False))


if __name__ == '__main__':
    main()
