#!/usr/bin/env python3
"""Test script for Q&A endpoint."""

import hashlib
from src.db.session import get_sync_session
from src.db.models import ApiKey, Document

# Get or create API key
with get_sync_session() as session:
    api_key = session.query(ApiKey).first()
    
    if not api_key:
        # Create test API key
        test_key = "test-api-key-12345"
        key_hash = hashlib.sha256(test_key.encode()).hexdigest()
        api_key = ApiKey(
            name="Test Key",
            key_hash=key_hash,
            is_active=True
        )
        session.add(api_key)
        session.commit()
        print(f"Created API key: {test_key}")
    else:
        # For existing key, we can't get the original (it's hashed)
        # Let's create a known one
        test_key = "test-api-key-12345"
        key_hash = hashlib.sha256(test_key.encode()).hexdigest()
        
        existing = session.query(ApiKey).filter(ApiKey.key_hash == key_hash).first()
        if not existing:
            api_key = ApiKey(
                name="Test Key",
                key_hash=key_hash,
                is_active=True
            )
            session.add(api_key)
            session.commit()
        print(f"Using API key: {test_key}")
    
    # Get completed documents
    docs = session.query(Document).filter(Document.status == 'completed').all()
    
    if not docs:
        print("\nNo completed documents found. Please upload and process a document first.")
        exit(1)
    
    print(f"\nCompleted documents ({len(docs)}):")
    for i, doc in enumerate(docs, 1):
        print(f"  {i}. {doc.filename} (ID: {doc.id}, Records: {doc.record_count})")
    
    print(f"\n=== Test Q&A Endpoint ===")
    print(f"\nStart the API server:")
    print(f"  uv run uvicorn src.api.main:app --reload --host 0.0.0.0 --port 8000")
    print(f"\nThen test with curl:")
    print(f"""
curl -X POST http://localhost:8000/query \\
  -H "X-API-Key: test-api-key-12345" \\
  -H "Content-Type: application/json" \\
  -d '{{
    "query": "What is the project structure?",
    "include_context": true
  }}'
""")
    
    print(f"\nOr test specific document:")
    if docs:
        doc_id = docs[0].id
        print(f"""
curl -X POST http://localhost:8000/query \\
  -H "X-API-Key: test-api-key-12345" \\
  -H "Content-Type: application/json" \\
  -d '{{
    "query": "What information is in this document?",
    "document_ids": ["{doc_id}"],
    "include_context": true
  }}'
""")
    
    print(f"\nOr use Swagger UI: http://localhost:8000/docs")
