#!/usr/bin/env python3
"""
Daytona Automobil — Script de découverte réseau
Intercepte toutes les réponses JSON pendant le chargement de /inventory
pour identifier les endpoints API qui fournissent le stock.
"""

import asyncio
import json
from playwright.async_api import async_playwright

TARGET_URL = "https://daytona-automobil.se/inventory"

async def main():
    found_apis = []

    async def on_response(response):
        ct = response.headers.get("content-type", "")
        if "application/json" in ct and response.status == 200:
            try:
                body = await response.json()
                entry = {
                    "url": response.url,
                    "status": response.status,
                    "preview": str(body)[:1000]
                }
                found_apis.append(entry)
                print(f"  ✓ JSON : {response.url}")
            except Exception:
                pass

    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()
        page.on("response", on_response)

        print(f"  🔍 Chargement de {TARGET_URL} ...")
        await page.goto(TARGET_URL, wait_until="networkidle")
        await page.wait_for_timeout(3000)

        print(f"\n  📊 {len(found_apis)} réponse(s) JSON interceptée(s)")
        for i, api in enumerate(found_apis):
            print(f"\n  [{i+1}] {api['url']}")
            print(f"      Status: {api['status']}")
            print(f"      Preview: {api['preview'][:200]}...")

        await browser.close()

    # Sauvegarder le résultat complet
    with open("daytona_discovery_result.json", "w", encoding="utf-8") as f:
        json.dump(found_apis, f, ensure_ascii=False, indent=2)
    print(f"\n  ✅ Résultat sauvegardé dans daytona_discovery_result.json")

if __name__ == "__main__":
    asyncio.run(main())
