"""Smoke tests for the Studio entry point.

These tests verify that:

- The Studio modules import cleanly without a display server (no Qt
  classes are instantiated at module level).
- ``arautopilot.studio.app.run(['--seed-demo', '--data-dir', tmp])``
  populates a fresh user store and exits 0 without launching a GUI.

GUI behaviour (login modal, main window, Flash Console widget rendering)
is covered by manual smoke testing -- pytest is intentionally headless
here.
"""

from __future__ import annotations

from pathlib import Path


def test_studio_modules_import_cleanly() -> None:
    # Importing these must not require a display server.
    from arautopilot.studio import app  # noqa: F401
    from arautopilot.studio import flash_console  # noqa: F401
    from arautopilot.studio import login_window  # noqa: F401
    from arautopilot.studio import main_window  # noqa: F401
    from arautopilot.studio import session  # noqa: F401


def test_seed_demo_via_app_run(tmp_path: Path) -> None:
    from arautopilot.core.user_store import UserStore
    from arautopilot.studio.app import run

    rc = run(["--seed-demo", "--data-dir", str(tmp_path)])
    assert rc == 0
    store = UserStore(tmp_path / "users.json")
    assert len(store) == 4
    sa = store.find_by_name("Alvaro")
    assert sa is not None
    assert sa.verify_pin("1111")


def test_seed_demo_is_idempotent(tmp_path: Path) -> None:
    from arautopilot.core.user_store import UserStore
    from arautopilot.studio.app import run

    assert run(["--seed-demo", "--data-dir", str(tmp_path)]) == 0
    assert run(["--seed-demo", "--data-dir", str(tmp_path)]) == 0
    store = UserStore(tmp_path / "users.json")
    assert len(store) == 4


def test_flash_console_helper_finds_pio_or_returns_path() -> None:
    """`_find_pio` must return a Path object even if the venv path doesn't
    exist (falls back to the bare 'pio' name)."""
    from arautopilot.studio.flash_console import _find_pio
    p = _find_pio()
    assert p is not None
    # We don't assert existence -- the function falls back to the bare name.
    from pathlib import Path as _P
    assert isinstance(p, _P)


def test_list_serial_ports_is_safe_to_call() -> None:
    """It must work whether or not pyserial finds ports."""
    from arautopilot.studio.flash_console import list_serial_ports
    result = list_serial_ports()
    assert isinstance(result, list)
    for entry in result:
        assert isinstance(entry, tuple)
        assert len(entry) == 2
