"""
Module: test_sandbox_connection
Description: Tests for sandbox connection resolution and sidecar file management.

Implements:
    - docs/cli/reference.md#huitzo-sandbox
    - docs/cli/agent-integration.md#sandbox-lifecycle
"""

from __future__ import annotations

from pathlib import Path

import pytest

from huitzo_cli.sandbox.connection import (
    cleanup_sidecar,
    read_sidecar,
    resolve_sandbox,
    write_sidecar,
)


class TestSidecarRoundtrip:
    """Test write_sidecar / read_sidecar roundtrip."""

    def test_write_and_read(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "sandbox.pid"
        pidfile.write_text("999")

        write_sidecar(pidfile, "http://localhost:8080", "secret-token", 5)
        data = read_sidecar(pidfile)

        assert data is not None
        assert data["url"] == "http://localhost:8080"
        assert data["token"] == "secret-token"
        assert data["commands"] == 5
        assert "pid" in data

    def test_write_with_none_token(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "sandbox.pid"
        pidfile.write_text("999")

        write_sidecar(pidfile, "http://localhost:8080", None, 0)
        data = read_sidecar(pidfile)

        assert data is not None
        assert data["token"] is None


class TestReadSidecar:
    """Test read_sidecar edge cases."""

    def test_returns_none_when_missing(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "nonexistent.pid"
        assert read_sidecar(pidfile) is None

    def test_returns_none_for_corrupt_json(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "sandbox.pid"
        sidecar = pidfile.with_suffix(".json")
        sidecar.write_text("{broken json")

        assert read_sidecar(pidfile) is None


class TestCleanupSidecar:
    """Test cleanup_sidecar removes the file."""

    def test_removes_sidecar(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "sandbox.pid"
        write_sidecar(pidfile, "http://localhost:8080", "tok", 1)
        sidecar = pidfile.with_suffix(".json")
        assert sidecar.exists()

        cleanup_sidecar(pidfile)
        assert not sidecar.exists()

    def test_noop_when_missing(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "nonexistent.pid"
        # Should not raise
        cleanup_sidecar(pidfile)


class TestResolveSandbox:
    """Test resolve_sandbox() priority logic."""

    def test_explicit_url_returned_directly(self) -> None:
        url, token = resolve_sandbox(sandbox_url="http://explicit:9999", sandbox_token="t")
        assert url == "http://explicit:9999"
        assert token == "t"

    def test_explicit_url_without_token(self) -> None:
        url, token = resolve_sandbox(sandbox_url="http://explicit:9999")
        assert url == "http://explicit:9999"
        assert token is None

    def test_reads_from_sidecar(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "sandbox.pid"
        pidfile.write_text("123")
        write_sidecar(pidfile, "http://sidecar:8080", "sidecar-tok", 3)

        url, token = resolve_sandbox(pidfile=pidfile)
        assert url == "http://sidecar:8080"
        assert token == "sidecar-tok"

    def test_raises_when_nothing_found(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "nonexistent.pid"
        with pytest.raises(RuntimeError, match="No running sandbox found"):
            resolve_sandbox(pidfile=pidfile)
