"""Rehearse backup, quarantine and a known-good file in a fresh computer folder.

This program does not access USB or emulate an ESP32. It leaves its fresh folder
for inspection and never removes a pre-existing learner directory.
"""
from pathlib import Path
import shutil
import subprocess
import sys
import uuid


def quarantine_app(device, backup):
    device = Path(device).resolve()
    original = device / 'main.py'
    disabled = device / 'main.disabled.py'
    if original.resolve().parent != device or disabled.resolve().parent != device:
        raise ValueError('Recovery filenames must stay inside the selected folder.')
    if not original.is_file():
        raise FileNotFoundError('main.py is missing.')
    if disabled.exists():
        raise FileExistsError('Choose an unused quarantine name; nothing was renamed.')
    if not Path(backup).is_file() or Path(backup).read_bytes() != original.read_bytes():
        raise ValueError('A matching computer backup is required before renaming.')
    original.rename(disabled)
    return disabled


def run_file(path):
    return subprocess.run([sys.executable, str(path)], capture_output=True, text=True,
                          timeout=10, encoding='utf-8', errors='replace')


def rehearse(base=None):
    base = Path(base) if base else Path(__file__).resolve().parent
    base = base.resolve()
    if not base.is_dir():
        raise ValueError('Choose an existing parent folder for the rehearsal.')
    root = base / ('ml-c10-rehearsal-' + uuid.uuid4().hex[:10])
    if root.resolve().parent != base:
        raise ValueError('The fresh rehearsal folder must stay inside its parent.')
    root.mkdir(exist_ok=False)
    device = root / 'simulated_board'; device.mkdir()
    backup_dir = root / 'computer_backup'; backup_dir.mkdir()
    sources = Path(__file__).resolve().parent
    original = device / 'main.py'
    shutil.copyfile(sources / 'broken_main.py', original)
    keep = device / 'keep.txt'; keep.write_text('Unrelated data stays unchanged.\n', encoding='utf-8')
    before = original.read_bytes()
    failed = run_file(original)
    assert failed.returncode != 0 and 'ML-C10 rehearsal failure' in failed.stderr
    print('PASS 1: deliberate application failure identified')
    backup = backup_dir / 'main.before-recovery.py'
    shutil.copyfile(original, backup)
    disabled = quarantine_app(device, backup)
    assert backup.read_bytes() == before and disabled.read_bytes() == before
    print('PASS 2: original backed up and kept under an unused name')
    shutil.copyfile(sources / 'ready_main.py', original)
    ready = run_file(original)
    assert ready.returncode == 0 and ready.stdout.splitlines() == ['ML-C10 ready']
    print('PASS 3: known small program prints ML-C10 ready')
    assert keep.read_text(encoding='utf-8') == 'Unrelated data stays unchanged.\n'
    assert backup.read_bytes() == disabled.read_bytes() == before
    print('PASS 4: backup, disabled original and unrelated data preserved')
    print('Inspect the rehearsal folder:', root)
    return root


if __name__ == '__main__':
    rehearse()
