"""
CLI functionality tests.
Tests the command-line interface without actually running full pipeline.
"""

import pytest
import sys
from io import StringIO
from unittest.mock import patch, MagicMock


def test_cli_main_import():
    """Test that CLI main function can be imported."""
    from ytqgen.cli import main
    assert callable(main)


def test_cli_help_command():
    """Test that --help works."""
    from ytqgen.cli import main
    
    with patch('sys.argv', ['ytqgen', '--help']):
        with pytest.raises(SystemExit) as exc_info:
            main()
        assert exc_info.value.code == 0


def test_cli_version_command():
    """Test that --version works."""
    from ytqgen.cli import main
    
    with patch('sys.argv', ['ytqgen', '--version']):
        with pytest.raises(SystemExit):
            main()


def test_cli_process_command_help():
    """Test that process --help works."""
    from ytqgen.cli import main
    
    with patch('sys.argv', ['ytqgen', 'process', '--help']):
        with pytest.raises(SystemExit) as exc_info:
            main()
        assert exc_info.value.code == 0


def test_cli_validate_youtube_url_valid():
    """Test YouTube URL validation with valid URL."""
    from ytqgen.cli import validate_youtube_url
    
    valid_urls = [
        "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
        "https://youtube.com/watch?v=dQw4w9WgXcQ",
        "https://youtu.be/dQw4w9WgXcQ",
        "https://m.youtube.com/watch?v=dQw4w9WgXcQ",
    ]
    
    for url in valid_urls:
        assert validate_youtube_url(url) == True


def test_cli_validate_youtube_url_invalid():
    """Test YouTube URL validation with invalid URL."""
    from ytqgen.cli import validate_youtube_url
    
    invalid_urls = [
        "https://vimeo.com/123456",
        "https://example.com/video.mp4",
        "not_a_url",
        "/path/to/video.mp4",
    ]
    
    for url in invalid_urls:
        with pytest.raises(ValueError, match="Only YouTube URLs are supported"):
            validate_youtube_url(url)


def test_cli_process_without_input(clean_env):
    """Test that process command requires --input."""
    from ytqgen.cli import cmd_process
    from argparse import Namespace
    
    args = Namespace(
        input=None,
        output=None,
        config=None,
        provider=None,
        transcription_provider=None,
        openai_key=None,
        mistral_key=None,
        groq_key=None,
        num_questions=None,
        mcq_percentage=None,
        subjective_percentage=None
    )
    
    exit_code = cmd_process(args)
    
    # Should return non-zero exit code
    assert exit_code != 0


def test_cli_apply_config():
    """Test that apply_config sets environment variables correctly."""
    from ytqgen.cli import apply_config
    import os
    
    config = {
        "provider": "groq",
        "transcription_provider": "groq",
        "keys": {
            "groq": "test_key_123"
        },
        "generation": {
            "num_questions": 15,
            "question_types": {
                "mcq_percentage": 30,
                "subjective_percentage": 70
            }
        }
    }
    
    apply_config(config)
    
    assert os.getenv("LLM_PROVIDER") == "groq"
    assert os.getenv("TRANSCRIPTION_PROVIDER") == "groq"


def test_cli_validate_api_keys_missing():
    """Test that missing API keys are detected."""
    from ytqgen.cli import validate_api_keys
    import os
    
    # Clear all API keys
    old_keys = {}
    for key in ["OPENAI_API_KEY", "MISTRAL_API_KEY", "GROQ_API_KEY"]:
        old_keys[key] = os.environ.pop(key, None)
    
    os.environ["LLM_PROVIDER"] = "groq"
    os.environ["TRANSCRIPTION_PROVIDER"] = "groq"
    
    try:
        with pytest.raises(ValueError, match="API key missing"):
            validate_api_keys()
    finally:
        # Restore keys
        for key, value in old_keys.items():
            if value:
                os.environ[key] = value


def test_cli_process_command_structure():
    """Test that process command has correct structure."""
    from ytqgen.cli import main
    import argparse
    
    # This test just checks the parser doesn't crash
    # Actual functionality tested in integration tests
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='command')
    
    # Simulate what main() does
    process_parser = subparsers.add_parser('process')
    process_parser.add_argument('--input', required=True)
    process_parser.add_argument('--output')
    process_parser.add_argument('--config')
    
    # Test parsing valid args
    args = parser.parse_args(['process', '--input', 'https://youtube.com/watch?v=test'])
    assert args.command == 'process'
    assert args.input == 'https://youtube.com/watch?v=test'
