from __future__ import annotations

from pathlib import Path

from autosana_cli.models import Platform, Session
from autosana_cli.state import StateStore


def make_session(session_id: str = "ios-4723-20260319T120000Z") -> Session:
    return Session(
        session_id=session_id,
        platform=Platform.IOS,
        device_name="iPhone 16 Pro",
        device_udid="SIM-1",
        appium_port=4723,
        appium_pid=123,
        tunnel_url="https://abc.trycloudflare.com",
        tunnel_pid=456,
        aux_port=8100,
        appium_log_path="/tmp/appium.log",
        tunnel_log_path="/tmp/tunnel.log",
        project_root="/tmp/project",
        started_at="2026-03-19T12:00:00Z",
    )


def test_state_round_trip(tmp_path: Path) -> None:
    store = StateStore(root_dir=tmp_path / ".autosana")
    session = make_session()

    store.save_sessions([session])
    loaded = store.load_sessions()

    assert loaded == [session]


def test_prune_dead_sessions_removes_inactive_entries(tmp_path: Path) -> None:
    store = StateStore(root_dir=tmp_path / ".autosana")
    alive = make_session("ios-4723-20260319T120000Z")
    dead = make_session("ios-4724-20260319T120001Z")
    dead.appium_port = 4724
    dead.aux_port = 8101
    store.save_sessions([alive, dead])

    remaining, removed = store.prune_dead_sessions(lambda session: session.session_id == alive.session_id)

    assert remaining == [alive]
    assert removed == [dead]
    assert store.load_sessions() == [alive]


def test_remove_matching_returns_removed_sessions(tmp_path: Path) -> None:
    store = StateStore(root_dir=tmp_path / ".autosana")
    ios = make_session("ios-4723-20260319T120000Z")
    android = make_session("android-4724-20260319T120000Z")
    android.platform = Platform.ANDROID
    android.appium_port = 4724
    android.aux_port = 8200
    store.save_sessions([ios, android])

    remaining, removed = store.remove_matching(lambda session: session.platform is Platform.IOS)

    assert remaining == [android]
    assert removed == [ios]
