#!/usr/bin/env python3
"""
cert_trust/cli.py

Command-line interface for cert-trust
"""
import sys
import json
from pathlib import Path

from . import core


def print_status(data: dict, verbose: bool = False) -> None:
    """Pretty-print status information."""
    try:
        from rich.console import Console
        from rich.table import Table
        from rich.panel import Panel
        
        console = Console()
        
        # Python status
        py = data["python"]
        py_status = "Enabled" if py["effective"] else "Disabled"
        py_color = "green" if py["effective"] else "red"
        
        table = Table(title="cert-trust Status", show_header=True)
        table.add_column("Target", style="cyan", no_wrap=True)
        table.add_column("Status", style="bold")
        table.add_column("Details")
        
        table.add_row(
            "Python",
            f"[{py_color}]{py_status}[/{py_color}]",
            f".pth files: {len(py['pth_files'])}"
        )
        
        # curl status
        curl = data["curl"]
        if curl["available"]:
            curl_status = "Available"
            if curl.get("uses_windows_store", False):
                details = "Uses Windows Certificate Store"
            elif curl.get("ca_bundle"):
                details = f"Bundle: {curl['ca_bundle']}"
            else:
                details = "No bundle detected"
        else:
            curl_status = "Not installed"
            details = ""
        
        curl_color = "green" if curl["available"] else "yellow"
        table.add_row("curl", f"[{curl_color}]{curl_status}[/{curl_color}]", details)
        
        console.print(table)
        
        if verbose:
            console.print("\n[bold]Platform:[/bold]", data["platform"])
            console.print("[bold]Python:[/bold]", data["python_version"])
            if py["pth_files"]:
                console.print("\n[bold].pth files:[/bold]")
                for p in py["pth_files"]:
                    console.print(f"  • {p}")
            if py["has_truststore"]:
                console.print("\n[dim]truststore package is installed[/dim]")
    
    except ImportError:
        # Fallback to simple text output if rich is not installed
        print(f"Platform: {data['platform']} | Python: {data['python_version']}")
        print(f"\nPython trust: {'ENABLED' if data['python']['effective'] else 'DISABLED'}")
        print(f"  .pth files: {len(data['python']['pth_files'])}")
        
        if data["curl"]["available"]:
            print(f"\ncurl: AVAILABLE")
            if data["curl"]["ca_bundle"]:
                print(f"  CA bundle: {data['curl']['ca_bundle']}")
        else:
            print(f"\ncurl: NOT INSTALLED")
        
        if verbose:
            print(f"\nDetails:\n{json.dumps(data, indent=2)}")


def print_result(data: dict, success_msg: str = None, error_msg: str = None) -> int:
    """Print operation result and return exit code."""
    try:
        from rich.console import Console
        console = Console()
        
        if data.get("success"):
            console.print(f"[OK] {success_msg or 'Success'}", style="bold green")
            return 0
        else:
            console.print(f"[FAIL] {error_msg or 'Failed'}", style="bold red")
            if "message" in data:
                console.print(f"  {data['message']}", style="red")
            return 1
    
    except ImportError:
        if data.get("success"):
            print(f"[OK] {success_msg or 'Success'}")
            return 0
        else:
            print(f"[FAIL] {error_msg or 'Failed'}")
            if "message" in data:
                print(f"  {data['message']}")
            return 1


def main():
    """Main CLI entry point."""
    import argparse
    
    parser = argparse.ArgumentParser(
        prog="cert-trust",
        description="Manage CA certificate trust for Python and curl",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s enable                    Enable system CA trust
  %(prog)s disable                   Disable system CA trust
  %(prog)s status -v                 Show detailed status
  %(prog)s add /path/to/ca.crt       Add a custom CA certificate
  %(prog)s verify https://example.com  Test TLS trust
        """
    )
    
    parser.add_argument("--version", action="version", version="%(prog)s 1.0.0")
    
    subparsers = parser.add_subparsers(dest="command", help="Command to execute")
    
    # enable command
    subparsers.add_parser("enable", help="Enable system CA trust for Python")
    
    # disable command
    subparsers.add_parser("disable", help="Disable system CA trust for Python")
    
    # status command
    status_parser = subparsers.add_parser("status", help="Show current trust status")
    status_parser.add_argument("-v", "--verbose", action="store_true", help="Show detailed information")
    status_parser.add_argument("--json", action="store_true", help="Output as JSON")
    
    # add command
    add_parser = subparsers.add_parser("add", help="Add a custom CA certificate")
    add_parser.add_argument("cert_path", help="Path to .crt, .pem, or .cer file")
    add_parser.add_argument("--json", action="store_true", help="Output as JSON")
    
    # verify command
    verify_parser = subparsers.add_parser("verify", help="Test TLS trust for a URL")
    verify_parser.add_argument("url", help="HTTPS URL to test")
    verify_parser.add_argument("--json", action="store_true", help="Output as JSON")
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return 1
    
    # Execute commands
    if args.command == "enable":
        result = core.enable()
        if result.get("already_enabled"):
            return print_result(result, success_msg="Already enabled")
        return print_result(result, success_msg="Enabled successfully")
    
    elif args.command == "disable":
        result = core.disable()
        if not result.get("was_enabled"):
            return print_result(result, success_msg="Already disabled")
        return print_result(result, success_msg="Disabled successfully")
    
    elif args.command == "status":
        result = core.status()
        if args.json:
            print(json.dumps(result, indent=2))
        else:
            print_status(result, verbose=args.verbose)
        return 0
    
    elif args.command == "add":
        cert_path = Path(args.cert_path)
        if not cert_path.exists():
            print(f"[FAIL] File not found: {cert_path}", file=sys.stderr)
            return 1
        
        result = core.add_cert(str(cert_path))
        
        if args.json:
            print(json.dumps(result, indent=2))
            return 0 if result.get("success") else 1
        
        if result.get("success"):
            print(f"[OK] Certificate added successfully: {cert_path.name}")
            if "results" in result:
                for key, res in result["results"].items():
                    if isinstance(res, dict) and res.get("success"):
                        print(f"  [OK] {key}")
            return 0
        else:
            print(f"[FAIL] Failed to add certificate")
            if "message" in result:
                print(f"  {result['message']}")
            if "results" in result:
                for key, res in result["results"].items():
                    if isinstance(res, dict):
                        if res.get("success"):
                            print(f"  [OK] {key}")
                        else:
                            print(f"  [FAIL] {key}: {res.get('message', 'Failed')}")
            return 1
    
    elif args.command == "verify":
        result = core.verify(args.url)
        
        if args.json:
            print(json.dumps(result, indent=2))
        else:
            print(f"Testing: {result['url']}\n")
            
            # curl result
            if "curl" in result:
                curl_ok = result["curl"].get("success", False)
                status = "OK" if curl_ok else "FAIL"
                color = "green" if curl_ok else "red"
                
                try:
                    from rich.console import Console
                    Console().print(f"[{status}] curl: ", style=f"bold {color}", end="")
                    if curl_ok:
                        print(f"HTTP {result['curl'].get('http_code', '???')}")
                    else:
                        print(f"FAILED - {result['curl'].get('error', 'Unknown error')}")
                except ImportError:
                    if curl_ok:
                        print(f"[{status}] curl: HTTP {result['curl'].get('http_code', '???')}")
                    else:
                        print(f"[{status}] curl: FAILED - {result['curl'].get('error', 'Unknown error')}")
            
            # Python result
            if "python" in result:
                py_ok = result["python"].get("success", False)
                status = "OK" if py_ok else "FAIL"
                
                try:
                    from rich.console import Console
                    Console().print(f"[{status}] Python: ", style=f"bold {'green' if py_ok else 'red'}", end="")
                    if py_ok:
                        print(f"HTTP {result['python'].get('http_code', '???')}")
                    else:
                        print(f"FAILED - {result['python'].get('error', 'Unknown error')}")
                except ImportError:
                    if py_ok:
                        print(f"[{status}] Python: HTTP {result['python'].get('http_code', '???')}")
                    else:
                        print(f"[{status}] Python: FAILED - {result['python'].get('error', 'Unknown error')}")
        
        # Return 0 if both succeeded or if json mode
        if args.json:
            return 0
        
        both_ok = (
            result.get("curl", {}).get("success", False) and 
            result.get("python", {}).get("success", False)
        )
        return 0 if both_ok else 1
    
    return 0


if __name__ == "__main__":
    sys.exit(main())
