"""Tests for CLI entry points: `python -m loom` and `loom` console script."""

from __future__ import annotations

import os
import stat
import subprocess
import sys
import sysconfig
from pathlib import Path

import pytest


def _clear_pth_hidden_flags() -> None:
    """Clear macOS UF_HIDDEN flag on .pth files in site-packages.

    uv sets UF_HIDDEN on .pth files it creates.  Python 3.13's site.py
    skips files with this flag, breaking editable-install console scripts.
    Clearing the flag before invoking the console script works around the
    issue.  See loom/__main__.py for background.
    """
    if not hasattr(stat, "UF_HIDDEN") or not hasattr(os, "chflags"):
        return
    site_packages = Path(sysconfig.get_path("purelib"))
    for pth in site_packages.glob("*.pth"):
        try:
            st = os.lstat(pth)
            if getattr(st, "st_flags", 0) & stat.UF_HIDDEN:
                os.chflags(pth, st.st_flags & ~stat.UF_HIDDEN)
        except OSError:
            pass


def test_python_m_loom_help():
    """Running `python -m loom --help` should exit 0 and mention Loom."""
    result = subprocess.run(
        [sys.executable, "-m", "loom", "--help"],
        capture_output=True,
        text=True,
        timeout=30,
    )
    assert result.returncode == 0, (
        f"python -m loom --help failed:\nstdout={result.stdout}\nstderr={result.stderr}"
    )
    assert "Loom" in result.stdout, (
        f"Expected 'Loom' in output, got:\n{result.stdout}"
    )


def test_loom_console_script_help():
    """Running the ``loom`` console script should exit 0 and mention Loom.

    Uses the console script directly (not ``uv run``) to avoid uv re-syncing
    the venv and re-applying UF_HIDDEN on .pth files.
    """
    _clear_pth_hidden_flags()

    loom_bin = Path(sys.executable).resolve().parent / "loom"
    if not loom_bin.exists():
        pytest.skip(f"Console script not found at {loom_bin}")
    result = subprocess.run(
        [str(loom_bin), "--help"],
        capture_output=True,
        text=True,
        timeout=30,
    )
    assert result.returncode == 0, (
        f"loom --help failed:\nstdout={result.stdout}\nstderr={result.stderr}"
    )
    assert "Loom" in result.stdout, (
        f"Expected 'Loom' in output, got:\n{result.stdout}"
    )
