from src.cli.config_loader import load_config
from src.connectors.factory import create_connector


async def validate_config(args):
    from src.cli.machine_output import emit_error, emit_json, is_machine

    machine = is_machine(args)

    if not machine:
        print(f"🔍 Validating config: {args.config}")

    try:
        config = load_config(args.config)
        if not machine:
            print("✅ YAML Syntax Valid")
            print("✅ Structure Valid")

        target_config = config.get("target", {})
        connection_type = target_config.get("connection", {}).get("type")
        platform = target_config.get("platform")

        if connection_type == "playwright" or platform == "playwright":
            connector_type = "playwright"
        elif connection_type == "rest" or platform == "custom-rest":
            connector_type = "rest"
        else:
            connector_type = "rest"

        if not machine:
            print(
                f"ℹ️  Using {'Playwright' if connector_type == 'playwright' else 'REST'} Connector"
            )

        connector = create_connector(
            "playwright" if connector_type == "playwright" else "api", target_config
        )

        if hasattr(connector, "initialize"):
            await connector.initialize()

        if not machine:
            print("📡 Testing connectivity...")

        reachable = await connector.health_check()

        if hasattr(connector, "close"):
            await connector.close()

        if machine:
            emit_json(
                {
                    "config": args.config,
                    "valid": True,
                    "connector_type": connector_type,
                    "reachable": reachable,
                }
            )
        else:
            if reachable:
                print("✅ Target Reachable")
                print("✅ Connection Successful")
            else:
                print("❌ Target Unreachable")

    except Exception as e:
        if machine:
            emit_error("validation_failed", str(e))
        else:
            print(f"❌ Validation Failed: {e}")
