#!/usr/bin/env python3
"""
HTTPS Token Configuration Example

This example demonstrates how to generate and use an HTTPS configuration
with token authentication.

Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com
"""

import json
import subprocess
import sys
from pathlib import Path


def main() -> int:
    """Generate and test HTTPS token configuration."""
    base_dir = Path(__file__).resolve().parent
    output_dir = base_dir / "examples_configs"
    output_dir.mkdir(exist_ok=True)

    print("🔧 HTTPS Token Configuration Example")
    print("=" * 50)

    print("1. Generating HTTPS configuration with token authentication...")
    result = subprocess.run(
        [
            sys.executable,
            "-m",
            "mcp_proxy_adapter.cli.main",
            "sets",
            "https",
            "--modifiers",
            "token",
            "roles",
            "--port",
            "8443",
            "--output-dir",
            str(output_dir),
        ],
        capture_output=True,
        text=True,
    )

    if result.returncode != 0:
        print(f"❌ Error generating configuration: {result.stderr}")
        return 1

    print("✅ HTTPS configuration with token authentication generated")

    config_files = list(output_dir.glob("https_token_roles*.json"))
    if not config_files:
        print("❌ No configuration files found")
        return 1

    config_file = config_files[0]
    print(f"📁 Configuration file: {config_file}")

    print("\n2. Testing configuration (SimpleConfigValidator)...")
    try:
        from mcp_proxy_adapter.core.config.simple_config import SimpleConfig
        from mcp_proxy_adapter.core.config.simple_config_validator import (
            SimpleConfigValidator,
        )
        cfg = SimpleConfig(str(config_file))
        cfg.load()
        validator = SimpleConfigValidator(config_path=str(config_file))
        errors = validator.validate(cfg.model)
        if errors:
            # Allow expected errors: missing cert files (no certs generated), unknown roles (RoleUtils set)
            allowed = [
                "file not found",
                "unknown role",
                "Valid roles:",
            ]
            unexpected = [e for e in errors if not any(a in e.message for a in allowed)]
            if unexpected:
                print("❌ Configuration validation failed:")
                for e in errors:
                    print(f"   - {e.message}")
                return 1
            print("⚠️  Validation passed with expected warnings (cert files or role names).")
        else:
            print("✅ Configuration validation passed")
    except Exception as e:
        print(f"❌ Configuration validation failed: {e}")
        return 1

    print("\n3. Configuration content:")
    with open(config_file) as f:
        config = json.load(f)

    print(f"   Protocol: {config['server']['protocol']}")
    print(f"   Host: {config['server']['host']}")
    print(f"   Port: {config['server']['port']}")
    server = config.get("server", {})
    ssl = server.get("ssl") if isinstance(server.get("ssl"), dict) else {}
    print(f"   SSL: {'Enabled' if ssl else 'Disabled'}")
    auth = config.get("auth", {})
    print(f"   Token Auth: {'Enabled' if auth.get('use_token') else 'Disabled'}")
    print(f"   Roles: {'Enabled' if auth.get('use_roles') else 'Disabled'}")

    if auth.get("tokens"):
        print("\n4. Available authentication tokens (token -> roles):")
        for token, roles in auth["tokens"].items():
            print(f"   {token}: {roles}")

    print("\n🎉 HTTPS token configuration example completed!")
    print(f"📁 Configuration saved to: {config_file}")
    print("\n💡 To start the server:")
    print(f"   mcp-proxy-adapter server --config {config_file}")
    print("\n💡 To test with curl:")
    print("   curl -k https://localhost:8443/health")
    print(
        "   curl -k -H 'X-API-Key: admin-secret-key' https://localhost:8443/api/jsonrpc "
        "-d '{{\"jsonrpc\":\"2.0\",\"method\":\"echo\",\"params\":{{\"message\":\"Hello\"}},\"id\":1}}'"
    )

    return 0


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