import argparse
import json
from ai_testing_swarm.orchestrator import SwarmOrchestrator
from ai_testing_swarm.core.curl_parser import parse_curl


def normalize_request(payload: dict) -> dict:
    """
    Normalize input into execution-ready request.

    Supported formats:
    1. { "curl": "curl ..." }
    2. { "method": "...", "url": "...", "headers": {...}, "body": {...} }
    """

    # Case 1: raw curl input
    if "curl" in payload:
        return parse_curl(payload["curl"])

    # Case 2: already normalized
    required_keys = {"method", "url"}
    if required_keys.issubset(payload.keys()):
        return payload

    raise ValueError(
        "Invalid input format.\n"
        "Expected either:\n"
        "1) { \"curl\": \"curl ...\" }\n"
        "2) { \"method\": \"POST\", \"url\": \"...\", \"headers\": {}, \"body\": {} }"
    )


def main():
    parser = argparse.ArgumentParser(description="AI Testing Swarm CLI")
    parser.add_argument(
        "--input",
        required=True,
        help="Path to request.json"
    )

    args = parser.parse_args()

    # ------------------------------------------------------------
    # Load input JSON
    # ------------------------------------------------------------
    with open(args.input) as f:
        payload = json.load(f)

    # ------------------------------------------------------------
    # 🔴 NORMALIZE INPUT (THIS FIXES YOUR ERROR)
    # ------------------------------------------------------------
    request = normalize_request(payload)

    # ------------------------------------------------------------
    # Run swarm
    # ------------------------------------------------------------
    decision, results = SwarmOrchestrator().run(request)

    # ------------------------------------------------------------
    # Console output
    # ------------------------------------------------------------
    print("\n=== RELEASE DECISION ===")
    print(decision)

    print("\n=== TEST RESULTS ===")
    for r in results:
        response = r.get("response", {})
        status_code = response.get("status_code")

        print(
            f"{r.get('name'):25} "
            f"{str(status_code):5} "
            f"{r.get('reason')}"
        )


if __name__ == "__main__":
    main()
