#!/usr/bin/env python3
"""Live smoke test for the KQ support booking tool API.

Reads KQ_PB_URL and KQ_TOOL_TOKEN from the environment. Never prints the token.
Assumes at least one open future support slot exists (created by Ale during
deployment). Safe to run against the live PocketBase: it only creates idempotent
test holds for a fixed test conversation id.
"""

import json
import os
import urllib.error
import urllib.request

PB = os.environ.get("KQ_PB_URL", "http://127.0.0.1:8091").rstrip("/")
TOOL_TOKEN = os.environ.get("KQ_TOOL_TOKEN", "")
TEST_CONVERSATION = int(os.environ.get("KQ_TEST_CONVERSATION", "990001"))

if not TOOL_TOKEN:
    raise SystemExit("KQ_TOOL_TOKEN is required (value is never printed)")


def post(path, body):
    req = urllib.request.Request(
        PB + path, data=json.dumps(body).encode(), method="POST",
        headers={"Content-Type": "application/json", "X-KQ-Tool-Token": TOOL_TOKEN})
    try:
        with urllib.request.urlopen(req, timeout=15) as resp:
            return resp.status, json.loads(resp.read().decode() or "{}")
    except urllib.error.HTTPError as exc:
        return exc.code, json.loads(exc.read().decode() or "{}")


# 1. Search returns at most three slots, ordered by date then time.
status, body = post("/api/kq/support/search", {})
assert status == 200, (status, body)
slots = body.get("slots", [])
assert len(slots) <= 3, slots
ordered = sorted(slots, key=lambda s: (s["date"], s["time_start"]))
assert slots == ordered, ("slots not ordered", slots)
print(f"search ok ({len(slots)} slots)")

# 2. Holding the same slot twice with the same conversation is idempotent.
if slots:
    slot_id = slots[0]["id"]
    payload = {
        "slot_id": slot_id, "student_name": "Smoke Test", "contact_phone": "2910000000",
        "education_level": "primary", "school_year": "5to", "topic": "smoke",
        "conversation_id": TEST_CONVERSATION,
    }
    s1, b1 = post("/api/kq/support/hold", payload)
    s2, b2 = post("/api/kq/support/hold", payload)
    assert s1 == 200, (s1, b1)
    assert s2 == 200, (s2, b2)
    assert b1["booking_id"] == b2["booking_id"], (b1, b2)
    print("hold idempotency ok")
else:
    print("hold idempotency skipped (no open slots)")

# 3. An unknown slot is rejected.
s3, b3 = post("/api/kq/support/hold", {
    "slot_id": "nonexistentslotid", "student_name": "Smoke Test", "contact_phone": "2910000000",
    "education_level": "primary", "school_year": "5to", "topic": "smoke",
    "conversation_id": TEST_CONVERSATION + 1,
})
assert s3 in (404, 409), (s3, b3)
print("unknown slot rejected ok")

print("KQ support booking HTTP contract ok")
