#!/usr/bin/env python3
"""Replay Clutch's actual rules on synthetic inputs without collectors or models."""
import contextlib
import hashlib
import importlib.util
import io
import json
from collections import deque
from datetime import datetime, timedelta
from pathlib import Path
import sys


def load_source(repo):
    path = Path(repo) / 'scripts/cellular_security.py'
    spec = importlib.util.spec_from_file_location('clutch_replay_source', path)
    source = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = source
    with contextlib.redirect_stdout(sys.stderr):
        spec.loader.exec_module(source)
    return source, hashlib.sha256(path.read_bytes()).hexdigest()


def monitor_for(source):
    monitor = source.CellularSecurityMonitor.__new__(source.CellularSecurityMonitor)
    monitor.config = {'notifications': {'enabled': False}}
    monitor.analysis_status = {}
    monitor.tower_database = {}
    monitor.measurement_history = deque(maxlen=100)
    monitor.security_threats = []
    monitor.last_location = None
    monitor.signal_jump_threshold = 20
    monitor.signal_anomaly_threshold = 15
    monitor.tower_change_threshold = 5
    return monitor


def replay(repo):
    source, digest = load_source(repo)
    # Deliberately exercise the five rule stages, without loading/fitting models.
    source.ML_AVAILABLE = False
    start = datetime(2026, 10, 26, 12)

    def row(index, strength=-90, technology='GSM', cipher='A5/1'):
        tower = source.CellularTower('fixture', 'fixture', '001', '01', technology)
        return source.CellularMeasurement(
            start + timedelta(seconds=index), tower, strength,
            signal_quality=0, timing_advance=0,
            technology=technology, encryption_status=cipher)

    cases = {
        'signal_jump': (row(0), row(1, -62)),
        'threshold_boundary': (row(0), row(1, -70)),
        'disabled_cipher': (row(0), row(1, cipher='None')),
        'unknown_cipher': (row(0), row(1, cipher='Unknown')),
        'generation_drop': (row(0, technology='LTE', cipher='Unknown'), row(1, cipher='Unknown')),
        'stable': (row(0), row(1)),
        'combined': (row(0, technology='LTE', cipher='A5/1'), row(1, -62, cipher='None')),
    }
    expected = {
        'signal_jump': ['IMSI_CATCHER_SUSPECTED'],
        'threshold_boundary': [],
        'disabled_cipher': ['ENCRYPTION_DOWNGRADE', 'ENCRYPTION_DOWNGRADE'],
        'unknown_cipher': [],
        'generation_drop': ['FORCED_TECHNOLOGY_DOWNGRADE'],
        'stable': [],
        'combined': ['IMSI_CATCHER_SUSPECTED', 'ENCRYPTION_DOWNGRADE',
                     'FORCED_TECHNOLOGY_DOWNGRADE', 'ENCRYPTION_DOWNGRADE'],
    }
    results = {}
    for name, rows in cases.items():
        monitor = monitor_for(source)
        for measurement in rows:
            findings = monitor.analyze_measurement(measurement)
        assert [f.threat_type for f in findings] == expected[name], name
        assert len(monitor.measurement_history) == 2
        assert len(monitor.security_threats) == len(findings)
        results[name] = [{'type': f.threat_type, 'weight': f.confidence,
                          'evidence': f.evidence} for f in findings]
    monitor = monitor_for(source)
    rejected = monitor.analyze_measurement(row(0, float('nan')))
    assert rejected == [] and len(monitor.measurement_history) == 0
    assert monitor.analysis_status['measurement']['state'] == 'unavailable'
    results['invalid_signal'] = monitor.analysis_status['measurement']
    return {'source_sha256': digest, 'scope': 'Synthetic inputs; actual analyze_measurement and five rule stages; ML disabled; notifications disabled; no collector',
            'cases': results}


if __name__ == '__main__':
    if len(sys.argv) != 2:
        raise SystemExit('Usage: python3 clutch_pipeline_replay.py /path/to/clutch')
    print(json.dumps(replay(sys.argv[1]), indent=2))
