"""Server-side synthetic demo. Never executes profile changes.

Required environment: API_BASE_URL (including /v1), API_KEY, TEXT_MODEL_ALIAS.
Run: python knowledge-functions.py [--stream]
One test store/file is created; use only an authorized test project.
"""
import argparse
import json
import os
import time
import urllib.error
import urllib.request
import uuid

BASE = os.environ["API_BASE_URL"].rstrip("/")
KEY = os.environ["API_KEY"]
MODEL = os.environ["TEXT_MODEL_ALIAS"]


def request(path, body=None, *, multipart=None, operation_key=None):
    headers = {"Authorization": "Bearer " + KEY}
    if operation_key:
        headers["Idempotency-Key"] = operation_key
    if multipart:
        boundary = "demo-" + uuid.uuid4().hex
        headers["Content-Type"] = "multipart/form-data; boundary=" + boundary
        data = (f'--{boundary}\r\nContent-Disposition: form-data; name="purpose"\r\n\r\nassistants\r\n'
                f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="demo-guide.txt"\r\n'
                'Content-Type: text/plain\r\n\r\n'
                'Guide: configure_profile proposes a display name and language for user approval. Never execute changes.\r\n'
                f'--{boundary}--\r\n').encode()
    else:
        headers["Content-Type"] = "application/json"
        data = None if body is None else json.dumps(body).encode()
    # Persist the operation_key together with the exact body before sending in a real app.
    # A transport failure is not permission to retry with a new key.
    req = urllib.request.Request(BASE + path, headers=headers, data=data)
    try:
        response = urllib.request.urlopen(req, timeout=180)
    except urllib.error.HTTPError as error:
        raise RuntimeError(f"HTTP {error.code}; request_id={error.headers.get('X-Request-Id')}; "
                           + error.read().decode("utf-8", "replace")) from None
    with response:
        if "text/event-stream" not in response.headers.get("Content-Type", ""):
            return json.load(response)
        final = None
        lines = []

        def consume():
            nonlocal final
            data_lines = [line[5:].lstrip() for line in lines if line.startswith("data:")]
            payload = "\n".join(data_lines)
            if not payload or payload == "[DONE]":
                return
            event = json.loads(payload)
            kind = event.get("type")
            if kind in {"error", "response.failed", "response.incomplete"}:
                raise RuntimeError(f"Stream did not complete; request_id={response.headers.get('X-Request-Id')}")
            if kind == "response.completed":
                final = event["response"]
            # No function execution on function_call_arguments.delta, even if it looks valid.

        for raw in response:
            line = raw.decode("utf-8").rstrip("\r\n")
            if line:
                lines.append(line)
            else:
                consume()
                lines.clear()
        if lines:
            consume()
        if final is None or not final.get("usage"):
            raise RuntimeError("No final response/usage; reconcile before retry")
        return final


def main(stream):
    if os.environ.get("VS_ID"):
        store = {"id": os.environ["VS_ID"]}
        uploaded = None
    else:
        uploaded = request("/files", multipart=True)
        store = request("/vector_stores", {"name": "Demo setup guide " + uuid.uuid4().hex[:8]})
        request(f'/vector_stores/{store["id"]}/files', {"file_id": uploaded["id"]})
    for _ in range(30):
        attached = request(f'/vector_stores/{store["id"]}/files')["data"]
        file = next((item for item in attached if uploaded is None or item.get("file_id") == uploaded["id"]), None)
        if file and file["status"] == "completed":
            break
        if file and file["status"] == "failed":
            raise RuntimeError("File extraction failed")
        time.sleep(2)
    else:
        raise RuntimeError("File not ready within the bounded wait")
    function = {"type": "function", "name": "propose_setup_action", "strict": False,
        "description": "Propose settings for approval; never execute a change.",
        "parameters": {"type": "object", "properties": {
            "action_type": {"type": "string", "enum": ["configure_profile"]},
            "summary": {"type": "string"}, "values": {"type": "object"}},
            "required": ["action_type", "summary", "values"]}}
    search = {"type": "file_search", "vector_store_ids": [store["id"]]}
    body = {"model": MODEL, "stream": stream, "max_output_tokens": 500,
        "instructions": "Use the guide. Propose configuration for approval using the function; never execute or guess values.",
        "input": [{"role": "user", "content": "Propose setting my display name to Demo and language to English."}],
        "tools": [search, function], "tool_choice": {"type": "function", "name": function["name"]}}
    first = request("/responses", body, operation_key=str(uuid.uuid4()))
    history = body["input"] + first["output"]
    count = 0
    for item in first["output"]:
        if item["type"] != "function_call":
            continue
        if item["name"] != function["name"]:
            raise ValueError("Unknown function")
        args = json.loads(item["arguments"])
        if (not isinstance(args, dict) or set(args) != {"action_type", "summary", "values"}
            or args["action_type"] != "configure_profile"
            or not isinstance(args["summary"], str) or not isinstance(args["values"], dict)):
            raise ValueError("Invalid proposal")
        # This demonstration accepts no mutation. Your backend must validate allowed
        # fields, ownership and permissions and obtain explicit approval for real actions.
        result = {"executed": False, "status": "awaiting_user_confirmation", "proposal": args}
        history.append({"type": "function_call_output", "call_id": item["call_id"], "output": json.dumps(result)})
        count += 1
    if not count:
        raise RuntimeError("Model returned no function call")
    continuation = {**body, "input": history, "tool_choice": "none"}
    final = request("/responses", continuation, operation_key=str(uuid.uuid4()))
    for item in final["output"]:
        for part in item.get("content", []):
            if part.get("type") == "output_text":
                print(part["text"])
    print("No changes executed. The demonstration file/store remains in your test project.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--stream", action="store_true")
    main(parser.parse_args().stream)
