"""
Verify that ttyd references have been fully removed from the Python codebase.

Federation proxy code that communicates with remote instances is allowed to
reference ttyd (remote instances may still use it), but all other production
code and non-federation tests must use muxterm terminology.
"""

import subprocess
from pathlib import Path

MUXPLEX_DIR = Path(__file__).resolve().parent.parent


# Files that are ALLOWED to contain "ttyd" because they deal with federation
# proxy code talking to remote instances (which may still run ttyd).
FEDERATION_ALLOWED = {
    "main.py",  # federation proxy comments about remote ttyd
    "tests/test_api.py",  # federation mock responses with ttyd_port
}

# Files excluded entirely from this check (they don't exist or are test-only guards).
EXCLUDED_FILES = {
    "tests/test_ttyd.py",
    "tests/test_ws_proxy.py",
    "tests/test_no_ttyd_refs.py",  # this file itself
    "tests/test_frontend_js.py",  # docstrings describe removed ttyd behavior
}


def _find_ttyd_refs():
    """Return list of (relative_path, line_no, line_text) tuples for non-allowed ttyd refs."""
    result = subprocess.run(
        ["grep", "-rn", "ttyd", str(MUXPLEX_DIR), "--include=*.py"],
        capture_output=True,
        text=True,
    )
    hits = []
    for line in result.stdout.strip().splitlines():
        if not line:
            continue
        # Format: /path/to/file.py:123:content
        parts = line.split(":", 2)
        if len(parts) < 3:
            continue
        filepath = Path(parts[0])
        lineno = parts[1]
        content = parts[2]

        # Skip __pycache__
        if "__pycache__" in str(filepath):
            continue

        rel = filepath.relative_to(MUXPLEX_DIR)
        rel_str = str(rel)

        # Skip excluded files
        if rel_str in EXCLUDED_FILES:
            continue

        # Skip federation-allowed files
        if rel_str in FEDERATION_ALLOWED:
            continue

        hits.append((rel_str, lineno, content.strip()))

    return hits


def test_no_ttyd_references_outside_federation():
    """No Python files (except federation proxy) should reference 'ttyd'."""
    hits = _find_ttyd_refs()
    if hits:
        details = "\n".join(f"  {f}:{ln}: {txt}" for f, ln, txt in hits)
        raise AssertionError(
            f"Found {len(hits)} remaining ttyd reference(s) outside federation code:\n{details}"
        )


def test_check_dependencies_no_ttyd():
    """_check_dependencies must only check for tmux, not ttyd."""
    from muxplex.cli import _check_dependencies
    import inspect

    source = inspect.getsource(_check_dependencies)
    assert "ttyd" not in source, (
        "_check_dependencies still references ttyd — it should only check for tmux"
    )


def test_doctor_no_ttyd_section():
    """doctor() must not contain a ttyd diagnostic section."""
    from muxplex.cli import doctor
    import inspect

    source = inspect.getsource(doctor)
    assert "ttyd" not in source, (
        "doctor() still contains ttyd references — the ttyd section should be removed"
    )
