#!/usr/bin/env python3
"""Test script for presigned download/preview URL endpoints.

Usage:
    python scripts/test_presigned_url.py <document_id>
    python scripts/test_presigned_url.py <document_id> --host http://localhost:8081
"""

import argparse
import json
import uuid

from dotenv import load_dotenv
load_dotenv()

import requests
from textiq_hmac import load_key_ring, sign_context_headers

DEFAULT_TENANT_ID = "28aa3971-48af-4f2a-aa73-9e4f89fbfba3"
DEFAULT_NODE_ID = "22222222-2222-2222-2222-222222222222"
DEFAULT_USER_ID = "33333333-3333-3333-3333-333333333333"
DEFAULT_ROLE = "content_specialist"


def sign_request(tenant_id, node_id, user_id, role):
    key_ring = load_key_ring()
    headers = {
        "X-Tenant-ID": tenant_id,
        "X-Node-ID": node_id,
        "X-User-ID": user_id,
        "X-Role": role,
    }
    return sign_context_headers(headers, key_ring)


def test_endpoint(host, endpoint_name, url, headers):
    print(f"\n--- {endpoint_name} ---")
    print(f"GET {url}")
    r = requests.get(url, headers=headers, timeout=30)
    print(f"  Status: {r.status_code}")
    try:
        data = r.json()
        print(f"  Body: {json.dumps(data, indent=2)}")
    except Exception:
        print(f"  Body: {r.text[:500]}")
    return r.status_code


def main():
    parser = argparse.ArgumentParser(description="Test presigned URL endpoints")
    parser.add_argument("document_id", help="Document UUID")
    parser.add_argument("--host", default="http://localhost:8081")
    parser.add_argument("--tenant-id", default=DEFAULT_TENANT_ID)
    parser.add_argument("--node-id", default=DEFAULT_NODE_ID)
    parser.add_argument("--user-id", default=DEFAULT_USER_ID)
    parser.add_argument("--role", default=DEFAULT_ROLE)
    args = parser.parse_args()

    print(f"=== Presigned URL Endpoint Tests ({args.host}) ===")
    print(f"Document: {args.document_id}")
    print(f"Tenant: {args.tenant_id}")

    headers = sign_request(args.tenant_id, args.node_id, args.user_id, args.role)
    headers["X-Correlation-ID"] = str(uuid.uuid4())

    # Test 1: download-url (happy path)
    s1 = test_endpoint(
        args.host, "Download URL (happy path)",
        f"{args.host}/api/v1/documents/{args.document_id}/download-url",
        headers,
    )

    # Test 2: preview-url (PDF should be inline)
    headers2 = sign_request(args.tenant_id, args.node_id, args.user_id, args.role)
    headers2["X-Correlation-ID"] = str(uuid.uuid4())
    s2 = test_endpoint(
        args.host, "Preview URL (PDF -> inline)",
        f"{args.host}/api/v1/documents/{args.document_id}/preview-url",
        headers2,
    )

    # Test 3: non-existent document
    fake_id = "00000000-0000-0000-0000-000000000000"
    headers3 = sign_request(args.tenant_id, args.node_id, args.user_id, args.role)
    headers3["X-Correlation-ID"] = str(uuid.uuid4())
    s3 = test_endpoint(
        args.host, "Non-existent document (expect 404)",
        f"{args.host}/api/v1/documents/{fake_id}/download-url",
        headers3,
    )

    # Test 4: invalid UUID
    headers4 = sign_request(args.tenant_id, args.node_id, args.user_id, args.role)
    headers4["X-Correlation-ID"] = str(uuid.uuid4())
    s4 = test_endpoint(
        args.host, "Invalid UUID (expect 422)",
        f"{args.host}/api/v1/documents/not-a-uuid/download-url",
        headers4,
    )

    # Test 5: wrong tenant
    wrong_tenant = "99999999-9999-9999-9999-999999999999"
    headers5 = sign_request(wrong_tenant, args.node_id, args.user_id, args.role)
    headers5["X-Correlation-ID"] = str(uuid.uuid4())
    s5 = test_endpoint(
        args.host, "Wrong tenant (expect 404)",
        f"{args.host}/api/v1/documents/{args.document_id}/download-url",
        headers5,
    )

    # Summary
    print("\n=== Summary ===")
    results = [
        ("Download URL (happy path)", s1, 200),
        ("Preview URL (PDF inline)", s2, 200),
        ("Non-existent doc", s3, 404),
        ("Invalid UUID", s4, 422),
        ("Wrong tenant", s5, 404),
    ]
    all_pass = True
    for name, got, expected in results:
        status = "PASS" if got == expected else "FAIL"
        if status == "FAIL":
            all_pass = False
        print(f"  {status}: {name} (expected {expected}, got {got})")

    print(f"\n{'All tests passed!' if all_pass else 'Some tests FAILED.'}")


if __name__ == "__main__":
    main()
