import asyncio
import os
import uuid
import json
from dotenv import load_dotenv
load_dotenv()

from app.services.chat.analytics import analyze_thread
from app.services.infra.database import bootstrap_tenant, get_db_connection
from app.services.integrations.firestore import db
from google.cloud import firestore
from datetime import datetime

async def test_sentiment_extraction():
    tenant_id = "org_dev_verification" 
    thread_id = f"test_thread_{uuid.uuid4().hex[:6]}"
    
    # Ensure schema is up to date
    bootstrap_tenant(tenant_id)
    
    print(f"--- Testing AI Sentiment Extraction for Thread: {thread_id} ---")
    
    # 1. Inject a mixed-sentiment conversation into Firestore (chat_history format)
    messages = [
        {"role": "user", "content": "Hello, I really love your platform! The UI is so smooth and clean. Great job on the design.", "timestamp": datetime.utcnow().isoformat()},
        {"role": "assistant", "content": "Thank you so much! We put a lot of effort into the UI. Is there anything else I can help with?", "timestamp": datetime.utcnow().isoformat()},
        {"role": "user", "content": "Well, actually, I am quite frustrated with the pricing page. It keeps crashing when I try to select a plan. This is a dealbreaker for me.", "timestamp": datetime.utcnow().isoformat()},
        {"role": "assistant", "content": "I'm very sorry to hear that. I've logged this major issue for our team to fix immediately.", "timestamp": datetime.utcnow().isoformat()}
    ]
    
    # Write to Firestore in the format expected by get_chat_history
    doc_ref = db.collection("chat_history").document(f"{tenant_id}_{thread_id}")
    doc_ref.set({
        "tenant_id": tenant_id,
        "thread_id": thread_id,
        "messages": messages,
        "updated_at": datetime.utcnow().isoformat()
    })
    print("1. Injected mixed conversation into Firestore.")

    try:
        # 2. Run analysis
        print("2. Running AI analysis...")
        success = await analyze_thread(tenant_id, thread_id)
        assert success, "Analysis failed"
        print("Analysis completed successfully.")

        # 3. Verify results in Postgres
        conn = get_db_connection()
        with conn.cursor() as cur:
            cur.execute(f"SELECT sentiment_score, positive_points, key_concerns, pain_point FROM {tenant_id}.strategist_thread_analytics WHERE thread_id = %s", (thread_id,))
            row = cur.fetchone()
            print("\n--- AI Extractions ---")
            print(f"Sentiment Score: {row[0]}")
            print(f"Positive Points: {row[1]}")
            print(f"Key Concerns: {row[2]}")
            print(f"Legacy Pain Point: {row[3]}")
            
            # Check for logical consistency
            assert row[1] is not None and "smooth" in row[1].lower(), "Failed to capture positive design feedback"
            assert row[2] is not None and "pricing" in row[2].lower(), "Failed to capture negative pricing issue"
            
        print("\n4. AI Extraction verification successful.")

    except Exception as e:
        print(f"\n--- VERIFICATION FAILED: {e} ---")
        raise
    finally:
        # Clean up Firestore (optional)
        # thread_ref.delete()
        if 'conn' in locals():
            conn.close()

if __name__ == "__main__":
    asyncio.run(test_sentiment_extraction())
