"""
Tests for Feature 14: One-Command Install / CLI.
  - duckclaw --help exits 0
  - duckclaw --version prints version string
  - duckclaw status without config exits non-zero
  - duckclaw start --help exits 0
All tests use subprocess so we get the real CLI entry point.
"""

import subprocess
import sys
import pytest


def _run(*args, env=None) -> subprocess.CompletedProcess:
    """Run `duckclaw <args>` in a subprocess and return the result."""
    return subprocess.run(
        [sys.executable, "-m", "duckclaw.cli"] + list(args),
        capture_output=True,
        text=True,
        timeout=30,
        env=env,
    )


def _run_entry(*args, env=None) -> subprocess.CompletedProcess:
    """Run via the installed `duckclaw` entry point (or fallback to module)."""
    try:
        return subprocess.run(
            ["duckclaw"] + list(args),
            capture_output=True,
            text=True,
            timeout=30,
            env=env,
        )
    except FileNotFoundError:
        return _run(*args, env=env)


class TestCLIHelp:
    """--help and sub-command --help exit cleanly."""

    def test_duckclaw_help_exits_zero(self):
        """duckclaw --help exits with code 0."""
        result = _run_entry("--help")
        assert result.returncode == 0
        output = result.stdout + result.stderr
        assert "duckclaw" in output.lower() or "usage" in output.lower()

    def test_duckclaw_start_help_exits_zero(self):
        """duckclaw start --help exits with code 0."""
        result = _run_entry("start", "--help")
        assert result.returncode == 0

    def test_duckclaw_chat_help_exits_zero(self):
        """duckclaw chat --help exits with code 0."""
        result = _run_entry("chat", "--help")
        assert result.returncode == 0

    def test_duckclaw_status_help_exits_zero(self):
        """duckclaw status --help exits with code 0."""
        result = _run_entry("status", "--help")
        assert result.returncode == 0


class TestCLIVersion:
    """--version prints the package version."""

    def test_duckclaw_version_prints_version(self):
        """duckclaw --version outputs a version string and exits 0."""
        result = _run_entry("--version")
        assert result.returncode == 0
        output = result.stdout + result.stderr
        # Should contain a version-like string (digits + dots)
        import re
        assert re.search(r"\d+\.\d+", output), f"No version number found in: {output!r}"


class TestCLINoConfig:
    """Commands that require config fail gracefully when config is absent."""

    def test_status_without_config_exits_nonzero(self, tmp_path, monkeypatch):
        """duckclaw status with no config file exits non-zero."""
        import os

        # Point home to an empty temp dir so no config is found
        env = os.environ.copy()
        env["HOME"] = str(tmp_path)

        result = subprocess.run(
            [sys.executable, "-m", "duckclaw.cli", "status"],
            capture_output=True,
            text=True,
            timeout=30,
            env=env,
            cwd=str(tmp_path),  # No duckclaw.yaml in cwd either
        )

        assert result.returncode != 0


class TestCLIImports:
    """The CLI module imports without errors — catches import-time regressions."""

    def test_cli_module_imports_cleanly(self):
        """python -c 'from duckclaw.cli import main' exits 0."""
        result = subprocess.run(
            [sys.executable, "-c", "from duckclaw.cli import main; print('OK')"],
            capture_output=True,
            text=True,
            timeout=15,
        )
        assert result.returncode == 0
        assert "OK" in result.stdout
