#!/usr/bin/env python3
"""
probe_kling_features.py — Phase 0 schema discovery for Kling multi-prompt + Elements.

Probes the Kling direct API (api.klingai.com) to determine:
1. Whether multi_prompt is accepted on /v1/videos/image2video or text2video
2. Whether element creation endpoints exist (/v1/elements, /elements)
3. Whether asset upload exists (/v1/assets)
4. Whether multi_shot boolean is needed

Uses valid JWT auth with intentionally invalid payloads to trigger
schema validation errors without generating video (zero cost).

Usage:
    python3 tools/probe_kling_features.py

Requires: KLING_ACCESS_KEY and KLING_SECRET_KEY environment variables.
"""

import json
import logging
import os
import sys
import time

# Add parent dir to path for lib imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from recoil.execution.api_client import KlingClient

logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)


def probe(client: KlingClient, description: str, method: str, path: str, body: dict = None):
    """Send a request and log the response for schema discovery."""
    logger.info("=== PROBE: %s ===", description)
    logger.info("  %s %s", method, path)
    if body:
        logger.info("  Body: %s", json.dumps(body, indent=2)[:500])

    try:
        response = client._request(method, path, body)
        logger.info("  SUCCESS: %s", json.dumps(response, indent=2)[:500])
        return {"status": "success", "response": response}
    except Exception as e:
        error_msg = str(e)
        logger.info("  ERROR: %s", error_msg[:500])
        return {"status": "error", "error": error_msg}


def main():
    client = KlingClient()
    if not client.is_available():
        logger.error("KLING_ACCESS_KEY and KLING_SECRET_KEY must be set")
        sys.exit(1)

    results = {}

    # Probe 1: Does image2video accept multi_prompt?
    results["multi_prompt_i2v"] = probe(
        client,
        "multi_prompt on /v1/videos/image2video",
        "POST", "/v1/videos/image2video",
        {
            "model_name": "kling-v3",
            "multi_prompt": [
                {"prompt": "test shot 1", "duration": 3},
                {"prompt": "test shot 2", "duration": 3},
            ],
            "aspect_ratio": "9:16",
            "mode": "std",
            "generate_audio": False,
        },
    )

    # Probe 2: Does text2video accept multi_prompt?
    results["multi_prompt_t2v"] = probe(
        client,
        "multi_prompt on /v1/videos/text2video",
        "POST", "/v1/videos/text2video",
        {
            "model_name": "kling-v3",
            "multi_prompt": [
                {"prompt": "test shot 1", "duration": 3},
                {"prompt": "test shot 2", "duration": 3},
            ],
            "aspect_ratio": "9:16",
            "mode": "std",
        },
    )

    # Probe 3: Does /v1/elements exist?
    results["elements_v1"] = probe(
        client,
        "Element creation at /v1/elements",
        "POST", "/v1/elements",
        {"name": "probe_test"},
    )

    # Probe 4: Does /elements exist?
    results["elements_root"] = probe(
        client,
        "Element creation at /elements",
        "POST", "/elements",
        {"name": "probe_test"},
    )

    # Probe 5: Does /v1/assets exist?
    results["assets"] = probe(
        client,
        "Asset upload at /v1/assets",
        "GET", "/v1/assets",
    )

    # Probe 6: Try with multi_shot boolean + shot_type
    results["multi_shot_bool"] = probe(
        client,
        "multi_prompt with multi_shot: true + shot_type: customize",
        "POST", "/v1/videos/text2video",
        {
            "model_name": "kling-v3",
            "multi_prompt": [
                {"prompt": "test", "duration": 3},
                {"prompt": "test", "duration": 3},
            ],
            "multi_shot": True,
            "shot_type": "customize",
            "aspect_ratio": "9:16",
            "mode": "std",
        },
    )

    # Summary
    print()
    print("=" * 60)
    print("PROBE RESULTS SUMMARY")
    print("=" * 60)
    for name, result in results.items():
        status = result["status"]
        if status == "error":
            detail = result.get("error", "")[:120]
        else:
            resp = result.get("response", {})
            detail = resp.get("message", resp.get("data", {}).get("task_id", ""))[:120]
        print(f"  {name:30s} {status:8s}  {detail}")

    # Interpretation guide
    print()
    print("=" * 60)
    print("HOW TO READ THESE RESULTS")
    print("=" * 60)
    print("""
  For each probe:
    - "error" with "unknown parameter" → endpoint doesn't support that param
    - "error" with param validation msg → endpoint DOES support it, needs valid values
    - "error" with 404             → endpoint doesn't exist
    - "success" with task_id       → it worked! (may have spent ~$0.45)

  Key decisions from results:
    - If multi_prompt_i2v shows param validation → use /v1/videos/image2video
    - If multi_prompt_t2v shows param validation → use /v1/videos/text2video
    - If both show "unknown parameter" → Plan B: switch to fal.ai
    - If elements_v1 shows param validation → use /v1/elements for pre-registration
    - If both element probes 404 → use inline elements only
    - If assets shows param validation → use /v1/assets for image hosting
    """)

    # Save results
    output_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "probe_results.json")
    with open(output_path, "w") as f:
        json.dump(results, f, indent=2, default=str)
    print(f"Results saved to: {output_path}")


if __name__ == "__main__":
    main()
