from __future__ import annotations

from pathlib import Path

import pytest

from autosana_cli import tunnel


def test_extract_tunnel_url() -> None:
    url = tunnel.extract_tunnel_url("INF route ready at https://abc-123.trycloudflare.com")
    assert url == "https://abc-123.trycloudflare.com"


def test_extract_tunnel_url_ignores_api_subdomain() -> None:
    text = 'Post "https://api.trycloudflare.com/tunnel": context deadline exceeded'
    assert tunnel.extract_tunnel_url(text) is None


def test_wait_for_tunnel_url_reads_log(tmp_path: Path) -> None:
    log_path = tmp_path / "tunnel.log"
    log_path.write_text("Ready at https://abc.trycloudflare.com\n", encoding="utf-8")
    assert tunnel.wait_for_tunnel_url(log_path, pid=999, timeout=0.1) == "https://abc.trycloudflare.com"


def test_wait_for_tunnel_url_fails_when_process_exits(tmp_path: Path, monkeypatch) -> None:
    log_path = tmp_path / "tunnel.log"
    monkeypatch.setattr(tunnel, "is_pid_running", lambda _pid: False)
    with pytest.raises(RuntimeError, match="exited"):
        tunnel.wait_for_tunnel_url(log_path, pid=999, timeout=0.1)
