"""
Test script: Goi API /api/product-desc/n8n-generate
Simulate n8n HTTP Request node gui data tu Google Sheets.

Chay: py backend/api/product_desc/test/test_n8n_desc.py
"""

import httpx
import json
import sys
import time

# Fix encoding for Windows
if sys.platform == "win32":
    sys.stdout.reconfigure(encoding="utf-8")

API_URL = "http://127.0.0.1:5000/api/product-desc/n8n-generate"

# ── Sample data giong het n8n gui tu Google Sheets ──
SAMPLE_PAYLOAD = {
    "ma_san_pham": "UNKNOWN",
    "ten_san_pham": "Ao ba lo",
    "image_url": "https://mdp.canifa.com/images-web/cache/e5/9b/e59b8c724757b142b3eb0d6ebf8d8f7f.jpg",
    "thanh_phan": "",
    "dac_tinh_chat_lieu": "",
    "mo_ta_chung": "",
    "tinh_nang": "",
    "kieu_dang": "",
    "hoan_canh": "",
    "featuring": "",
    "chung_chi": "",
    "huong_dan_su_dung": "",
}


def main():
    print("=" * 60)
    print("TEST: n8n Ultra Description API")
    print("=" * 60)

    # Step 1: Check server is running
    print("\n[1/3] Checking server...")
    try:
        r = httpx.get("http://127.0.0.1:5000/health", timeout=5)
        if r.status_code == 200:
            print("      Server OK")
        else:
            print(f"      Server returned {r.status_code}")
            sys.exit(1)
    except httpx.ConnectError:
        print("      Server NOT running at http://127.0.0.1:5000")
        print("      -> Start server first: py backend/server.py")
        sys.exit(1)

    # Step 2: Send request
    print(f"\n[2/3] POST {API_URL}")
    print(f"      Product: {SAMPLE_PAYLOAD['ten_san_pham']}")
    print(f"      Image URL: {SAMPLE_PAYLOAD['image_url'][:60]}...")

    t0 = time.time()
    try:
        r = httpx.post(API_URL, json=SAMPLE_PAYLOAD, timeout=120)
        elapsed = round(time.time() - t0, 2)
    except Exception as e:
        print(f"      ERROR: {e}")
        sys.exit(1)

    # Step 3: Parse response
    print(f"\n[3/3] Response (took {elapsed}s)")
    print(f"      Status: {r.status_code}")

    try:
        data = r.json()
    except Exception:
        print(f"      Raw: {r.text[:500]}")
        sys.exit(1)

    if data.get("status") == "success":
        print(f"      Product: {data.get('ten_san_pham')}")
        print(f"      Server elapsed: {data.get('elapsed_s')}s")

        ai_desc = data.get("ai_description", "")
        print(f"\n{'=' * 60}")
        print("AI DESCRIPTION:")
        print("=" * 60)
        print(ai_desc)
        print(f"\n{'=' * 60}")
        print(f"Length: {len(ai_desc)} chars")

        # Vision debug
        vd = data.get("vision_data", {})
        if vd:
            print(f"\nVision data: {json.dumps(vd, ensure_ascii=False, indent=2)}")

        print(f"\nKET QUA: OK")
    else:
        print(f"      ERROR: {data.get('message')}")
        if data.get("raw"):
            print(f"      Raw: {data['raw'][:300]}")
        sys.exit(1)


if __name__ == "__main__":
    main()
