# src/test_transition.py

import time
import psutil
from PIL import Image
from src.display_manager import DisplayManager
from src.config_manager import ConfigManager

PRESETS = {
    "snappy": {
        "type": "fade",
        "fade_duration": 0.3,
        "fade_steps": 5,
        "easing": True
    },
    "cinematic": {
        "type": "fade",
        "fade_duration": 0.8,
        "fade_steps": 12,
        "easing": True
    },
    "lightweight": {
        "type": "fade",
        "fade_duration": 0.4,
        "fade_steps": 4,
        "easing": False
    },
    "cut": {
        "type": "cut",
        "cut_duration": 0.2
    }
}


def benchmark_transition(dm, transition_func, *args, **kwargs):
    psutil.cpu_percent(interval=None)
    start = time.time()
    transition_func(*args, **kwargs)
    end = time.time()
    cpu = psutil.cpu_percent(interval=None)
    print(f"{transition_func.__name__} took {end - start:.2f}s, CPU ~{cpu:.1f}%")


def show_frame(dm, color, hold=0.5):
    frame = Image.new("RGB", (dm.width, dm.height), color)
    dm.image.paste(frame)
    dm.update_display()
    time.sleep(hold)


def run_preset(name, settings, dm):
    print(f"\n=== Testing preset: {name} ===")
    show_frame(dm, (255, 0, 0), hold=0.5)  # red start

    if settings["type"] == "fade":
        dur = settings.get("fade_duration", 0.4)
        steps = settings.get("fade_steps", 6)
        easing = settings.get("easing", True)

        benchmark_transition(dm, dm.fade_out, duration=dur, steps=steps, easing=easing)
        show_frame(dm, (0, 0, 255), hold=0.0)  # blue
        benchmark_transition(dm, dm.fade_in, duration=dur, steps=steps, easing=easing)

    elif settings["type"] == "cut":
        dur = settings.get("cut_duration", 0.2)
        benchmark_transition(dm, dm.cut_to_black, duration=dur)
        show_frame(dm, (0, 0, 255), hold=0.5)  # blue

    # After each preset, hold a 2‑second black screen
    show_frame(dm, (0, 0, 0), hold=2.0)


def main():
    config = ConfigManager().load_config()
    dm = DisplayManager(config)

    # Loop through all presets twice for stress test
    for cycle in range(2):
        print(f"\n### Cycle {cycle+1} ###")
        for name, settings in PRESETS.items():
            run_preset(name, settings, dm)

    print("\nAll presets tested.")


if __name__ == "__main__":
    main()
