#!/usr/bin/env python3
"""
mTLS Roles Configuration Example

This example demonstrates how to generate and use an mTLS configuration
with role-based access control.

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

import json
import subprocess
import sys
from pathlib import Path


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

    print("🔧 mTLS Roles Configuration Example")
    print("=" * 50)

    print("1. Generating mTLS configuration with roles...")
    result = subprocess.run(
        [
            sys.executable,
            "-m",
            "mcp_proxy_adapter.cli.main",
            "sets",
            "mtls",
            "--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("✅ mTLS configuration with roles generated")

    config_files = list(output_dir.glob("mtls_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:
            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']}")
    print(
        f"   SSL: {'Enabled' if config.get('ssl', {}).get('enabled') else 'Disabled'}"
    )
    print(
        f"   Client Verification: {'Enabled' if config.get('transport', {}).get('verify_client') else 'Disabled'}"
    )
    print(
        f"   Roles: {'Enabled' if config.get('roles', {}).get('enabled') else 'Disabled'}"
    )

    if config.get("ssl"):
        ssl_config = config["ssl"]
        print("\n4. SSL Configuration:")
        print(f"   Certificate: {ssl_config.get('cert_file', 'Not set')}")
        print(f"   Private Key: {ssl_config.get('key_file', 'Not set')}")
        print(f"   CA Certificate: {ssl_config.get('ca_cert', 'Not set')}")

    if config.get("roles", {}).get("enabled"):
        print("\n5. Roles Configuration:")
        print(
            f"   Config File: {config['roles'].get('config_file', 'Not set')}"
        )
        print(f"   Auto Load: {config['roles'].get('auto_load', False)}")
        print(
            f"   Validation: {'Enabled' if config['roles'].get('validation_enabled') else 'Disabled'}"
        )

    print("\n🎉 mTLS roles 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 (requires client certificates):")
    print("   curl -k --cert client.crt --key client.key https://localhost:8443/health")
    print(
        "   curl -k --cert client.crt --key client.key https://localhost:8443/api/jsonrpc "
        "-d '{{\"jsonrpc\":\"2.0\",\"method\":\"echo\",\"params\":{{\"message\":\"Hello mTLS\"}},\"id\":1}}'"
    )

    return 0


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