"""CLI argument parsing and version-check bypass logic."""

import argparse
import os

from cli_logging.cli_logger import emit_structured_log
from cli_logging.logging_utils import Operation
from common import MAX_CONCURRENCY, RunConfig, JUDGE_BACKEND_AZURE, JUDGE_BACKEND_GITHUB_COPILOT
from agent_selector import normalize_agent_id


# Flags that should bypass remote min-version enforcement.
# --help is not needed here because argparse exits before runtime checks.
VERSION_CHECK_BYPASS_FLAGS = (
    "signout",
)


def should_bypass_min_version_check(config: RunConfig) -> bool:
    """Return True if the current invocation should skip min-version checks."""
    return any(getattr(config, flag, False) for flag in VERSION_CHECK_BYPASS_FLAGS)


def parse_arguments():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description="M365 Copilot Agent Evaluation CLI",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Run with default prompts
  python main.py

  # Run with custom prompts
  python main.py --prompts "What is Microsoft Graph?" --expected "Microsoft Graph is a gateway..."

  # Run with prompts from file
  python main.py --prompts-file prompts.json

  # Evaluate responses already captured in a v1 eval document
  python main.py --evaluate-only captured-evals.json

  # Interactive mode
  python main.py --interactive

  # Save results to JSON
  python main.py --output results.json

  # Save results to CSV
  python main.py --output results.csv

  # Save results to HTML and open in browser
  python main.py --output report.html

  # Debug-level diagnostics
  python main.py --log-level debug

  # Sign out and clear cached authentication tokens
  python main.py --signout
        """
    )
    
    # Input options (mutually exclusive)
    input_group = parser.add_mutually_exclusive_group()
    input_group.add_argument(
        '--prompts', 
        nargs='+', 
        help='List of prompts to evaluate'
    )
    input_group.add_argument(
        '--prompts-file', 
        type=str, 
        help='JSON file containing prompts and expected responses'
    )
    input_group.add_argument(
        '--evaluate-only',
        type=str,
        help='Evaluate responses from a v1 eval document without invoking the agent'
    )
    input_group.add_argument(
        '--interactive', 
        action='store_true', 
        help='Interactive mode to enter prompts'
    )
    
    # Expected responses (only used with --prompts)
    parser.add_argument(
        '--expected', 
        nargs='+', 
        help='List of expected responses (must match number of prompts)'
    )
    
    # Agent ID (--m365-agent-id is primary, --agent-id kept for backward compatibility)
    parser.add_argument(
        '--m365-agent-id', '--agent-id',
        type=str,
        default=os.environ.get("M365_AGENT_ID") or os.environ.get("AGENT_ID"),
        help='Agent ID (default from M365_AGENT_ID environment variable)'
    )

    # Output options
    parser.add_argument(
        '--output', 
        type=str, 
        help='Output file path. Format is determined by file extension: .json, .csv, .html. If not provided, results are printed to console.'
    )
    
    # Behavior options
    parser.add_argument(
        '--log-level',
        nargs='?',
        const='info',
        action='append',
        help='Set log verbosity: debug, info, warning, error. Bare --log-level resolves to info.'
    )

    parser.add_argument(
        '--signout',
        action='store_true',
        help='Sign out and clear cached authentication tokens'
    )

    parser.add_argument(
        '--account',
        type=str,
        default=None,
        help='User account (email/UPN) to authenticate with when multiple accounts are cached (e.g. user@contoso.com). Pre-fills the sign-in picker if the account is not cached.'
    )

    parser.add_argument(
        '--azure-ai-auth-mode',
        type=str,
        choices=['key', 'default-credential'],
        default=None,
        help='Azure AI authentication mode: key or default-credential (auto-detects if omitted)'
    )

    parser.add_argument(
        '--concurrency',
        type=int,
        default=MAX_CONCURRENCY,
        help=f'Number of parallel workers for prompt processing (1-{MAX_CONCURRENCY}, default: {MAX_CONCURRENCY})'
    )

    parser.add_argument(
        '--judge-backend',
        type=str,
        choices=[JUDGE_BACKEND_AZURE, JUDGE_BACKEND_GITHUB_COPILOT],
        default=JUDGE_BACKEND_AZURE,
        help=f'LLM judge backend for evaluators: "{JUDGE_BACKEND_AZURE}" uses Azure OpenAI (default), "{JUDGE_BACKEND_GITHUB_COPILOT}" uses GitHub Copilot SDK (no Azure OpenAI keys needed)'
    )

    args = parser.parse_args()

    args.m365_agent_id = normalize_agent_id(args.m365_agent_id)

    if args.concurrency < 1:
        parser.error('--concurrency must be an integer >= 1.')
    if args.concurrency > MAX_CONCURRENCY:
        emit_structured_log(
            "warning",
            f"--concurrency {args.concurrency} exceeds max {MAX_CONCURRENCY}; clamping to {MAX_CONCURRENCY}.",
            operation=Operation.SETUP,
        )
        args.concurrency = MAX_CONCURRENCY

    return args
