from __future__ import annotations

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from claude_account_activity import account_has_live_session


def _proc(tmp_path: Path, pid: int, environ: bytes) -> Path:
    root = tmp_path / "proc"
    proc_dir = root / str(pid)
    proc_dir.mkdir(parents=True, exist_ok=True)
    (proc_dir / "environ").write_bytes(environ)
    return root


def test_no_matching_process_means_idle(tmp_path: Path) -> None:
    home = tmp_path / "CLAUDE_HOME"
    home.mkdir()
    root = _proc(tmp_path, 100, b"PATH=/usr/bin\x00CLAUDE_CONFIG_DIR=/somewhere/else\x00")

    assert account_has_live_session(home, proc_root=root) is False


def test_process_with_the_account_config_dir_means_live(tmp_path: Path) -> None:
    home = tmp_path / "CLAUDE_HOME"
    home.mkdir()
    root = _proc(tmp_path, 100, b"CLAUDE_CONFIG_DIR=" + str(home).encode() + b"\x00")

    assert account_has_live_session(home, proc_root=root) is True


def test_symlinked_config_dir_still_matches(tmp_path: Path) -> None:
    home = tmp_path / "CLAUDE_HOME"
    home.mkdir()
    alias = tmp_path / "alias"
    alias.symlink_to(home)
    root = _proc(tmp_path, 100, b"CLAUDE_CONFIG_DIR=" + str(alias).encode() + b"\x00")

    assert account_has_live_session(home, proc_root=root) is True


def test_unreadable_process_table_fails_closed(tmp_path: Path) -> None:
    home = tmp_path / "CLAUDE_HOME"
    home.mkdir()

    assert account_has_live_session(home, proc_root=tmp_path / "missing-proc") is True


def test_unreadable_single_environ_is_skipped(tmp_path: Path) -> None:
    home = tmp_path / "CLAUDE_HOME"
    home.mkdir()
    root = tmp_path / "proc"
    (root / "100").mkdir(parents=True)

    assert account_has_live_session(home, proc_root=root) is False
