#!/usr/bin/env python3
"""Test Dify with full error details"""
import urllib.request, json, ssl

ctx = ssl.create_default_context()
BASE = "https://itsupport.servyou.com.cn"

def api(method, path, data=None, token=None, timeout=60):
    url = f"{BASE}{path}"
    body = json.dumps(data).encode() if data else None
    req = urllib.request.Request(url, data=body, method=method)
    req.add_header("Content-Type", "application/json")
    if token:
        req.add_header("Authorization", f"Bearer {token}")
    try:
        resp = urllib.request.urlopen(req, context=ctx, timeout=timeout)
        raw = resp.read().decode()
        try:
            return resp.status, json.loads(raw)
        except json.JSONDecodeError:
            return resp.status, {"raw": raw}
    except urllib.request.HTTPError as e:
        raw = e.read().decode()
        try:
            return e.code, json.loads(raw)
        except json.JSONDecodeError:
            return e.code, {"raw": raw}

# Step 1: H5 mock login
print("=== Step 1: H5 Mock Login ===")
code, body = api("POST", "/api/h5/mock-login", {"employee_id": "emp001", "employee_name": "test"})
print(f"  Status: {code}")
print(f"  Response: {json.dumps(body, ensure_ascii=False)}")
h5_token = body.get("data", {}).get("token", "")

# Step 2: Get current conversation (with full error)
print("\n=== Step 2: Get Current Conversation ===")
code, body = api("GET", "/api/h5/conversations/current", token=h5_token)
print(f"  Status: {code}")
print(f"  Response: {json.dumps(body, ensure_ascii=False)}")

# Step 3: Try sending a message directly (POST /h5/conversations/current/messages)
# This should create a conversation if none exists
print("\n=== Step 3: Send Message (auto-create conversation) ===")
code, body = api("POST", "/api/h5/conversations/current/messages", {
    "content": "hello"
}, h5_token, timeout=90)
print(f"  Status: {code}")
print(f"  Response: {json.dumps(body, ensure_ascii=False)[:500]}")

# Step 4: After sending, check conversation again
print("\n=== Step 4: Get Conversation After Message ===")
code, body = api("GET", "/api/h5/conversations/current", token=h5_token)
print(f"  Status: {code}")
conv_data = body.get("data", {})
if conv_data:
    print(f"  Conversation ID: {conv_data.get('id')}")
    print(f"  Status: {conv_data.get('status')}")
    print(f"  AI reply count: {conv_data.get('ai_substantive_reply_count')}")
