"""
GuardRails CLI

Command-line interface for the GuardRails security scanner.
"""

import os
import sys
import json
from pathlib import Path
from typing import Optional

import click
from rich.console import Console
from rich.panel import Panel
from rich.text import Text

from .scanner import GuardRailsScanner

console = Console()


@click.group()
@click.version_option(version="1.0.0", prog_name="GuardRails")
def main():
    """🛡️ GuardRails Security Scanner - AI-powered vulnerability detection."""
    pass


@main.command()
@click.argument('target', type=click.Path(exists=True))
@click.option('-f', '--format', 'output_format', 
              type=click.Choice(['text', 'json', 'table']), 
              default='text', help='Output format')
@click.option('-o', '--output', type=click.Path(), help='Output file path')
@click.option('--fail-on-critical', is_flag=True, 
              help='Exit with error code if critical issues found')
@click.option('--ignore', default='node_modules,.git,dist,build,__pycache__,.pytest_cache',
              help='Comma-separated ignore patterns')
@click.option('--extensions', default='.py,.js,.ts,.jsx,.tsx,.java,.go,.php,.rb,.cs',
              help='Comma-separated file extensions to scan')
@click.option('--api-key', help='GuardRails API key')
@click.option('--server', default='http://localhost:3000', help='GuardRails server URL')
@click.option('--timeout', default=30, help='Request timeout in seconds')
def scan(target, output_format, output, fail_on_critical, ignore, extensions, api_key, server, timeout):
    """Scan files or directories for security vulnerabilities."""
    
    with console.status("Scanning for security vulnerabilities..."):
        try:
            scanner = GuardRailsScanner(api_key=api_key, base_url=server)
            
            options = {
                'ignore': ignore.split(','),
                'extensions': extensions.split(','),
                'timeout': timeout
            }
            
            results = scanner.scan(target, **options)
            report = scanner.format_report(results, output_format)
            
            if output:
                with open(output, 'w') as f:
                    f.write(report)
                console.print(f"📄 Report saved to: {output}")
            else:
                console.print(report)
            
            # Exit with error code if critical issues found
            if fail_on_critical and scanner.has_critical_issues(results):
                console.print("\n❌ Critical security issues found!")
                sys.exit(1)
                
        except Exception as e:
            console.print(f"[red]Error: {e}[/red]")
            sys.exit(1)


@main.command()
@click.option('--server', default='http://localhost:3000', help='GuardRails server URL')
def status(server):
    """Check GuardRails server status."""
    
    with console.status("Checking GuardRails server..."):
        try:
            scanner = GuardRailsScanner(base_url=server)
            status_info = scanner.check_server_status()
            
            console.print("✅ GuardRails server is running!")
            console.print(f"✅ Server: {server}")
            console.print(f"✅ Status: {status_info.get('status', 'OK')}")
            console.print(f"✅ Gemini AI: {status_info.get('gemini', 'Ready')}")
            
        except Exception as e:
            console.print(f"[red]❌ Server not accessible: {e}[/red]")
            console.print("\n💡 Start the server with: guardrails server start")
            sys.exit(1)


@main.command()
@click.option('--fail-on-critical', is_flag=True, 
              help='Block commits with critical issues')
def install_hook(fail_on_critical):
    """Install Git pre-commit hook for automatic scanning."""
    
    hook_content = f"""#!/bin/sh
# GuardRails pre-commit hook
echo "🔍 GuardRails: Scanning staged files..."

# Get staged files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\\.(py|js|ts|jsx|tsx|java|go|php|rb|cs)$')

if [ -z "$STAGED_FILES" ]; then
  echo "✅ No relevant files to scan"
  exit 0
fi

# Run GuardRails scan
guardrails scan . --format text {'--fail-on-critical' if fail_on_critical else ''}

if [ $? -ne 0 ]; then
  echo "❌ GuardRails scan failed!"
  exit 1
fi

echo "✅ GuardRails scan passed!"
"""
    
    hook_path = Path('.git/hooks/pre-commit')
    
    try:
        hook_path.parent.mkdir(parents=True, exist_ok=True)
        hook_path.write_text(hook_content)
        hook_path.chmod(0o755)
        
        console.print("✅ Git pre-commit hook installed successfully!")
        console.print("GuardRails will now scan your code before each commit.")
        
    except Exception as e:
        console.print(f"[red]Failed to install hook: {e}[/red]")
        sys.exit(1)


@main.command()
def init():
    """Initialize GuardRails in your project."""
    
    config = {
        "version": "1.0.0",
        "scan": {
            "extensions": [".py", ".js", ".ts", ".jsx", ".tsx", ".java", ".go", ".php", ".rb", ".cs"],
            "ignore": ["node_modules/**", ".git/**", "dist/**", "build/**", "__pycache__/**", ".pytest_cache/**"],
            "failOnCritical": True
        },
        "ci": {
            "enabled": True,
            "output": "guardrails-report.json"
        }
    }
    
    config_path = Path('guardrails.config.json')
    
    try:
        config_path.write_text(json.dumps(config, indent=2))
        console.print("✅ GuardRails configuration created!")
        console.print("📄 Edit guardrails.config.json to customize your settings.")
        
        # Add to requirements.txt if it exists
        requirements_path = Path('requirements.txt')
        if requirements_path.exists():
            requirements_content = requirements_path.read_text()
            if 'guardrails-security' not in requirements_content:
                requirements_path.write_text(requirements_content + '\nguardrails-security>=1.0.0\n')
                console.print("✅ Added guardrails-security to requirements.txt!")
        
        # Create .guardrailsignore if it doesn't exist
        ignore_path = Path('.guardrailsignore')
        if not ignore_path.exists():
            ignore_content = """# GuardRails ignore patterns
node_modules/
.git/
dist/
build/
__pycache__/
.pytest_cache/
*.pyc
*.pyo
*.pyd
.coverage
.pytest_cache/
"""
            ignore_path.write_text(ignore_content)
            console.print("✅ Created .guardrailsignore file!")
        
    except Exception as e:
        console.print(f"[red]Failed to initialize: {e}[/red]")
        sys.exit(1)


@main.command()
@click.option('--port', default=3000, help='Server port')
@click.option('--host', default='localhost', help='Server host')
def server(port, host):
    """Start the GuardRails server (requires backend setup)."""
    
    console.print("🚀 Starting GuardRails server...")
    console.print(f"📡 Server will be available at: http://{host}:{port}")
    console.print("\n💡 Note: This requires the GuardRails backend to be set up.")
    console.print("   For full functionality, deploy the backend server separately.")
    
    # This would typically start the backend server
    # For now, just show instructions
    console.print("\n📋 To set up the full backend:")
    console.print("   1. Clone the GuardRails repository")
    console.print("   2. Install dependencies: pip install -r requirements.txt")
    console.print("   3. Set up environment variables")
    console.print("   4. Run: python -m guardrails.server")


if __name__ == '__main__':
    main()
