#!/usr/bin/env python3
"""
Verify config generator and validator against the config settings graph.

Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com
"""
from __future__ import annotations

import json
import sys
import tempfile
from pathlib import Path

from mcp_proxy_adapter.core.config.config_graph import check_config_against_graph
from mcp_proxy_adapter.core.config.simple_config import SimpleConfig
from mcp_proxy_adapter.core.config.simple_config_validator import SimpleConfigValidator
from mcp_proxy_adapter.examples.config_factory import (
    create_http_simple,
    create_http_token,
    create_https_simple,
    create_mtls_simple,
)


def run_graph_check(config: dict, label: str) -> list[tuple[str, str]]:
    """Run graph check; return list of (path, message)."""
    return check_config_against_graph(config)


def run_validator(config_path: str, config_dict: dict) -> list[str]:
    """Load config from path, validate model; return list of error messages."""
    cfg = SimpleConfig(config_path)
    cfg.load()
    validator = SimpleConfigValidator(config_path=config_path)
    errors = validator.validate(cfg.model)
    return [e.message for e in errors]


def main() -> int:
    """Verify generator outputs satisfy graph and validator agrees where expected."""
    print("🔍 Config graph verification: generator and validator")
    print("=" * 60)
    failed = 0

    # 1) Generator outputs must pass graph check (no missing required keys)
    cases = [
        ("http_simple", create_http_simple(port=8080, log_dir="./logs")),
        ("http_token", create_http_token(port=8080, api_keys={"admin": "admin-key"})),
        (
            "https_simple",
            create_https_simple(port=8443, cert_dir="./certs", key_dir="./keys"),
        ),
        (
            "mtls_simple",
            create_mtls_simple(port=8443, cert_dir="./certs", key_dir="./keys"),
        ),
    ]
    for name, cfg in cases:
        graph_errors = run_graph_check(cfg, name)
        if graph_errors:
            print(f"❌ {name}: graph check failed")
            for path, msg in graph_errors:
                print(f"   - {path}: {msg}")
            failed += 1
        else:
            print(f"✅ {name}: graph check passed")

    # 2) Validator: config that passes graph should pass validator for structure
    #    (validator may still fail on file existence for SSL certs)
    with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as f:
        tmp_path = f.name
    try:
        cfg = create_http_simple(port=8080, log_dir="./logs")
        Path(tmp_path).write_text(json.dumps(cfg, indent=2))
        val_errors = run_validator(tmp_path, cfg)
        if val_errors:
            print(f"\n⚠️  Validator on http_simple reported: {val_errors}")
            # Not necessarily a failure: e.g. log_dir path might be checked
        else:
            print("\n✅ Validator accepted http_simple config")
    finally:
        Path(tmp_path).unlink(missing_ok=True)

    print("=" * 60)
    if failed:
        print(f"❌ {failed} graph check(s) failed")
        return 1
    print("✅ All graph checks passed")
    return 0


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