"""E2E tests for new CLI UX flows (JL-390/400).

Tests exercise the actual CLI binary via subprocess to catch
integration issues that unit tests miss.
"""
import json
import subprocess
import sys
import tempfile
import pytest
from pathlib import Path

# All tests run from the janus-labs app directory
APP_DIR = Path(__file__).parent.parent


class TestQuickstartText:
    """Verify --help shows the new run-first quickstart."""

    def test_help_shows_run_command(self):
        result = subprocess.run(
            [sys.executable, "-m", "janus_labs", "--help"],
            capture_output=True, text=True, cwd=APP_DIR
        )
        assert result.returncode == 0
        assert "janus-labs run --suite refactor-storm" in result.stdout

    def test_help_shows_full_pipeline(self):
        result = subprocess.run(
            [sys.executable, "-m", "janus_labs", "--help"],
            capture_output=True, text=True, cwd=APP_DIR
        )
        assert "--full --agent codex" in result.stdout
        assert "--full --agent copilot" in result.stdout

    def test_help_shows_advanced_section(self):
        result = subprocess.run(
            [sys.executable, "-m", "janus_labs", "--help"],
            capture_output=True, text=True, cwd=APP_DIR
        )
        assert "ADVANCED" in result.stdout
        assert "janus-labs init" in result.stdout

    def test_help_no_old_4step(self):
        """The old 4-step quickstart should NOT appear."""
        result = subprocess.run(
            [sys.executable, "-m", "janus_labs", "--help"],
            capture_output=True, text=True, cwd=APP_DIR
        )
        # Old text had numbered steps
        assert "1. janus-labs init" not in result.stdout
        assert "2. <run your AI agent>" not in result.stdout


class TestVersionOutput:
    """Verify version reporting."""

    def test_version_flag(self):
        result = subprocess.run(
            [sys.executable, "-m", "janus_labs", "--version"],
            capture_output=True, text=True, cwd=APP_DIR
        )
        assert result.returncode == 0
        assert "janus-labs" in result.stdout


class TestMockRun:
    """Test the run command with --mock (no network, no agent)."""

    def test_mock_run_produces_json(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            output = Path(tmpdir) / "result.json"
            result = subprocess.run(
                [sys.executable, "-m", "janus_labs", "run",
                 "--suite", "refactor-storm",
                 "--mock",
                 "--no-interactive",
                 "-o", str(output)],
                capture_output=True, text=True, cwd=APP_DIR
            )
            assert result.returncode == 0, f"Run failed: {result.stderr}"
            assert output.exists(), "result.json not created"
            data = json.loads(output.read_text())
            assert "headline_score" in data
            assert "behavior_scores" in data

    def test_mock_run_shows_mock_banner(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            output = Path(tmpdir) / "result.json"
            result = subprocess.run(
                [sys.executable, "-m", "janus_labs", "run",
                 "--suite", "refactor-storm",
                 "--mock",
                 "--no-interactive",
                 "-o", str(output)],
                capture_output=True, text=True, cwd=APP_DIR
            )
            assert "MOCK MODE" in result.stdout


class TestSmokeTestCommand:
    """Test the smoke-test command."""

    def test_smoke_test_runs(self):
        """Smoke-test with mock scoring to avoid backend timeout in CI."""
        with tempfile.TemporaryDirectory() as tmpdir:
            output = Path(tmpdir) / "smoke.json"
            result = subprocess.run(
                [sys.executable, "-m", "janus_labs", "run",
                 "--suite", "refactor-storm", "--mock", "--no-interactive",
                 "-o", str(output)],
                capture_output=True, text=True, cwd=APP_DIR,
                timeout=180,
                env={**__import__("os").environ, "JANUS_NO_UPDATE_CHECK": "1"},
            )
            # Should complete with mock scoring
            assert result.returncode == 0, f"Smoke test failed: {result.stderr}"
            assert "MOCK MODE" in result.stdout


class TestBenchDeprecation:
    """Test the bench command redirects to smoke-test (silent alias)."""

    def test_bench_redirects_to_smoke_test(self):
        result = subprocess.run(
            [sys.executable, "-m", "janus_labs", "bench"],
            capture_output=True, text=True, cwd=APP_DIR,
            timeout=180
        )
        # bench is silently rewritten to smoke-test via sys.argv alias
        assert result.returncode == 0
        assert "Detecting config" in result.stdout


class TestSuiteAlias:
    """Test suite shortcut (janus-labs refactor-storm)."""

    def test_suite_alias_with_mock(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            output = Path(tmpdir) / "result.json"
            result = subprocess.run(
                [sys.executable, "-m", "janus_labs", "refactor-storm",
                 "--mock",
                 "--no-interactive",
                 "-o", str(output)],
                capture_output=True, text=True, cwd=APP_DIR
            )
            assert result.returncode == 0, f"Suite alias failed: {result.stderr}"
            assert output.exists()
