from __future__ import annotations

import shutil
import uuid
from pathlib import Path

from cliproom.cli import _print_status
from cliproom.cli_state import LocalCLIState


def _mk_state_dir() -> Path:
    path = Path(".test_state") / str(uuid.uuid4())
    path.mkdir(parents=True, exist_ok=True)
    return path


def test_status_no_state(capsys, monkeypatch) -> None:
    state_dir = _mk_state_dir()
    monkeypatch.setenv("CLIPROOM_STATE_DIR", str(state_dir))
    try:
        _print_status()
        out = capsys.readouterr().out
        assert "No local runtime state found." in out
    finally:
        shutil.rmtree(state_dir, ignore_errors=True)


def test_status_client_and_server(capsys, monkeypatch) -> None:
    state_dir = _mk_state_dir()
    monkeypatch.setenv("CLIPROOM_STATE_DIR", str(state_dir))
    try:
        state = LocalCLIState()
        state.write_state(
            {
                "active": True,
                "mode": "join",
                "status": "connected",
                "session": "devteam",
                "server_host": "127.0.0.1",
                "server_port": 4545,
                "client_name": "laptop",
                "pid": 999999,
                "updated_at": "now",
                "last_error": None,
            }
        )
        state.write_server_state(
            {
                "active": True,
                "status": "running",
                "fixed_session": "devteam",
                "host": "0.0.0.0",
                "port": 4545,
                "pid": 999998,
                "updated_at": "now",
                "last_error": None,
            }
        )

        _print_status()
        out = capsys.readouterr().out
        assert "[client]" in out
        assert "[server]" in out
        assert "session: devteam" in out
        assert "endpoint: 127.0.0.1:4545" in out
        assert "endpoint: 0.0.0.0:4545" in out
    finally:
        shutil.rmtree(state_dir, ignore_errors=True)
