"""Reproduce hypothetical capacity, dependency and latency examples.

Standard library only. No device access, network simulation or hardware claims.
Run: python design_checks.py
"""
from pathlib import Path
from math import ceil, floor, isfinite
import json


def capacity_lower_bound(demand, limits, utilization=0.8):
    """Valid only when loads can be partitioned across independent capacities."""
    if not 0 < utilization <= 1 or demand.keys() != limits.keys():
        raise ValueError('Invalid utilization or mismatched dimensions')
    per_dimension = {}
    for name, count in demand.items():
        if not isinstance(count, int) or count < 0 or limits[name] <= 0:
            raise ValueError('Invalid demand or limit')
        available = floor(limits[name] * utilization)
        if available < 1:
            raise ValueError('No usable capacity')
        per_dimension[name] = {
            'demand': count, 'available_per_gateway': available,
            'lower_bound': ceil(count / available),
        }
    return {'dimensions': per_dimension,
            'lower_bound': max((v['lower_bound'] for v in per_dimension.values()), default=0)}


def surviving_paths(paths, failed):
    """Assume each listed path is actually configured and reachable beforehand."""
    return [name for name, components in paths.items() if not set(components) & set(failed)]


def summarize(latencies_ms, deadline_ms=2000):
    """None is an unconfirmed attempt, not a measured infinite latency.

    Report a finite all-attempt P95 only when its nearest rank is within the
    confirmed samples. Late confirmations are censored at the deadline here.
    """
    if deadline_ms <= 0:
        raise ValueError('Deadline must be positive')
    if any(x is not None and (not isfinite(x) or x < 0) for x in latencies_ms):
        raise ValueError('Invalid latency')
    observed = sorted(x for x in latencies_ms if x is not None and x <= deadline_ms)
    n = len(latencies_ms)
    rank = ceil(0.95 * n)
    all_p95 = observed[rank - 1] if n and rank <= len(observed) else None
    return {
        'attempts': n, 'confirmed_by_deadline': len(observed),
        'unconfirmed_by_deadline': n - len(observed),
        'success_rate': len(observed) / n if n else None,
        'successful_only_p95_ms': observed[ceil(0.95 * len(observed)) - 1] if observed else None,
        'all_attempts_p95_ms': all_p95,
        'all_attempts_p95_status': 'no_data' if not n else ('observed' if all_p95 is not None else 'not_determined_within_deadline'),
        'deadline_ms': deadline_ms,
    }


def main():
    limits = dict(devices=100, elements=200, endpoints=100)
    base = capacity_lower_bound(dict(devices=80, elements=116, endpoints=68), limits)
    expanded = capacity_lower_bound(dict(devices=81, elements=117, endpoints=69), limits)
    endpoint_limited = capacity_lower_bound(dict(devices=40, elements=40, endpoints=81), limits)
    assert base['lower_bound'] == 1
    assert expanded['lower_bound'] == 2
    assert endpoint_limited['lower_bound'] == 2
    assert expanded['dimensions']['devices']['lower_bound'] == 2
    paths = {
        'A': ['controller', 'core', 'floor_switch', 'gateway_A', 'target'],
        'B': ['controller', 'core', 'floor_switch', 'gateway_B', 'target'],
    }
    one_failed = surviving_paths(paths, ['gateway_A'])
    shared_failed = surviving_paths(paths, ['floor_switch'])
    assert one_failed == ['B'] and shared_failed == []
    incomplete = summarize([200] * 90 + [None] * 10)
    assert incomplete['successful_only_p95_ms'] == 200
    assert incomplete['success_rate'] == 0.9
    assert incomplete['all_attempts_p95_ms'] is None
    assert summarize([])['successful_only_p95_ms'] is None
    assert summarize([None] * 100)['success_rate'] == 0
    assert summarize([200] * 100)['all_attempts_p95_ms'] == 200
    assert summarize([2001])['unconfirmed_by_deadline'] == 1
    assert summarize([2000])['confirmed_by_deadline'] == 1
    report = {
        'evidence_type': 'Executed deterministic software calculations on synthetic inputs; no hardware or radio tests',
        'capacity_assumptions': 'Independent capacities and partitionable loads; usable capacity=floor(limit*0.8)',
        'base_capacity': base, 'one_more_sensor': expanded,
        'endpoint_limited_counterexample': endpoint_limited,
        'dependency_assumptions': 'Paths already reachable; boolean availability only; no reconvergence timing',
        'gateway_A_failed_surviving_paths': one_failed,
        'floor_switch_failed_surviving_paths': shared_failed,
        'synthetic_latency_summary': incomplete,
        'edge_checks': 'Empty sample, zero success, full success, deadline boundary, late sample checked',
    }
    dest = Path(__file__).with_name('design-check-results.json')
    dest.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()
