#!/usr/bin/env python3
"""Test script for the document approve/reject endpoints on Airflow webserver.

Usage:
    # Approve a document
    python scripts/test_approval_endpoint.py approve <document_id>

    # Approve with a note
    python scripts/test_approval_endpoint.py approve <document_id> --note "Looks good"

    # Reject a document
    python scripts/test_approval_endpoint.py reject <document_id> --reason "Wrong file format, please re-upload"

    # Custom host
    python scripts/test_approval_endpoint.py --host http://localhost:8081 approve <document_id>

Requires HMAC_KEY_RING env var (or HMAC_KEY_RING_FILE) to be set.
"""

import argparse
import json
import sys
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):
    """Generate HMAC headers using textiq_hmac package."""
    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 approve_document(host, document_id, note, tenant_id, node_id, user_id, role):
    """POST /{document_id}/approve"""
    url = f"{host}/api/v1/documents/{document_id}/approve"
    headers = sign_request(tenant_id, node_id, user_id, role)
    headers["Content-Type"] = "application/json"
    headers["X-Correlation-ID"] = str(uuid.uuid4())

    body = {}
    if note:
        body["note"] = note

    print(f"POST {url}")
    print(f"  Document: {document_id}")
    print(f"  Tenant: {tenant_id}")
    print(f"  User: {user_id}")
    if note:
        print(f"  Note: {note}")

    r = requests.post(url, headers=headers, json=body, 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]}")

    if r.status_code == 200:
        print("  -> PASS: Document approved")
        if isinstance(data, dict):
            print(f"  approval_status: {data.get('approval_status')}")
            print(f"  dag_triggered: {data.get('dag_triggered')}")
    else:
        print(f"  -> FAIL: Expected 200, got {r.status_code}")


def reject_document(host, document_id, reason, tenant_id, node_id, user_id, role):
    """POST /{document_id}/reject"""
    url = f"{host}/api/v1/documents/{document_id}/reject"
    headers = sign_request(tenant_id, node_id, user_id, role)
    headers["Content-Type"] = "application/json"
    headers["X-Correlation-ID"] = str(uuid.uuid4())

    body = {"rejection_reason": reason}

    print(f"POST {url}")
    print(f"  Document: {document_id}")
    print(f"  Tenant: {tenant_id}")
    print(f"  User: {user_id}")
    print(f"  Reason: {reason}")

    r = requests.post(url, headers=headers, json=body, 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]}")

    if r.status_code == 200:
        print("  -> PASS: Document rejected")
        if isinstance(data, dict):
            print(f"  approval_status: {data.get('approval_status')}")
            print(f"  s3_deleted: {data.get('s3_deleted')}")
    else:
        print(f"  -> FAIL: Expected 200, got {r.status_code}")


def main():
    parser = argparse.ArgumentParser(description="Test document approve/reject endpoints")
    parser.add_argument("--host", default="http://localhost:8081", help="Airflow webserver URL")
    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)

    subparsers = parser.add_subparsers(dest="action", required=True)

    approve_parser = subparsers.add_parser("approve", help="Approve a document")
    approve_parser.add_argument("document_id", help="Document UUID")
    approve_parser.add_argument("--note", default=None, help="Optional approval note")

    reject_parser = subparsers.add_parser("reject", help="Reject a document")
    reject_parser.add_argument("document_id", help="Document UUID")
    reject_parser.add_argument("--reason", required=True, help="Rejection reason (10-500 chars)")

    args = parser.parse_args()

    print(f"=== Document Approval Test ({args.host}) ===\n")

    if args.action == "approve":
        approve_document(
            args.host, args.document_id, args.note,
            args.tenant_id, args.node_id, args.user_id, args.role,
        )
    elif args.action == "reject":
        reject_document(
            args.host, args.document_id, args.reason,
            args.tenant_id, args.node_id, args.user_id, args.role,
        )


if __name__ == "__main__":
    main()
