#!/usr/bin/env python3
"""
HTTP Basic Configuration Example

This example demonstrates how to generate and use a basic HTTP configuration.

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

import json
import subprocess
import sys
from pathlib import Path


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

    print("🔧 HTTP Basic Configuration Example")
    print("=" * 50)

    print("1. Generating HTTP configuration...")
    result = subprocess.run(
        [
            sys.executable,
            "-m",
            "mcp_proxy_adapter.cli.main",
            "sets",
            "http",
            "--port",
            "8080",
            "--output-dir",
            str(output_dir),
        ],
        capture_output=True,
        text=True,
    )

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

    print("✅ HTTP configuration generated")

    config_files = list(output_dir.glob("http*.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:
            print("❌ Configuration validation failed:")
            for e in errors:
                print(f"   - {e.message}")
            return 1
    except Exception as e:
        print(f"❌ Configuration validation failed: {e}")
        return 1
    print("✅ Configuration validation passed")

    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']}")
    auth = config.get("auth", {})
    print(
        f"   Auth token: {'Enabled' if auth.get('use_token') else 'Disabled'}"
    )

    print("\n🎉 HTTP basic 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}")

    return 0


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