import subprocess
import sys
import tempfile
from unittest.mock import patch


def test_version():
    result = subprocess.run(
        [sys.executable, "-m", "skilark_cli.main", "--version"],
        capture_output=True,
        text=True,
    )
    assert result.returncode == 0
    assert "skilark" in result.stdout.lower()


def test_unknown_command_exits_nonzero():
    result = subprocess.run(
        [sys.executable, "-m", "skilark_cli.main", "notacommand"],
        capture_output=True,
        text=True,
    )
    assert result.returncode == 1
    assert "unknown command" in result.stderr.lower()


def test_today_dispatches_to_run():
    """main() routes `today` (and default) to today.run() without error."""
    from skilark_cli.main import main

    with patch("skilark_cli.commands.today.run") as mock_run:
        main.__module__  # ensure import
        import sys as _sys
        _sys.argv = ["skilark", "today"]
        with patch.object(_sys, "argv", ["skilark", "today"]):
            main()

    mock_run.assert_called_once()


def test_status_first_run_message():
    """status exits cleanly with a setup hint when no config file exists."""
    with tempfile.TemporaryDirectory() as tmp:
        env = {**subprocess.os.environ, "SKILARK_CONFIG_DIR": tmp}
        result = subprocess.run(
            [sys.executable, "-m", "skilark_cli.main", "status"],
            capture_output=True,
            text=True,
            env=env,
        )
    assert result.returncode == 0
    assert "skilark today" in result.stdout.lower()


def test_config_first_run_message():
    """config exits cleanly with a setup hint when no config file exists."""
    with tempfile.TemporaryDirectory() as tmp:
        env = {**subprocess.os.environ, "SKILARK_CONFIG_DIR": tmp}
        result = subprocess.run(
            [sys.executable, "-m", "skilark_cli.main", "config"],
            capture_output=True,
            text=True,
            env=env,
        )
    assert result.returncode == 0
    assert "skilark today" in result.stdout.lower()
