"""
Test script for AI functions
Run this to verify all AI functions work with console logging
"""
import os
import sys
import django

# Setup Django
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../../../'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'igny8.settings')
django.setup()

from igny8_core.ai.functions.auto_cluster import AutoClusterFunction
from igny8_core.ai.functions.generate_images import generate_images_core
from igny8_core.ai.ai_core import AICore


def test_ai_core():
    """Test AICore.run_ai_request() directly"""
    print("\n" + "="*80)
    print("TEST 1: AICore.run_ai_request() - Direct API Call")
    print("="*80)
    
    ai_core = AICore()
    result = ai_core.run_ai_request(
        prompt="Say 'Hello, World!' in JSON format: {\"message\": \"your message\"}",
        max_tokens=100,
        function_name='test_ai_core'
    )
    
    if result.get('error'):
        print(f"❌ Error: {result['error']}")
    else:
        print(f"✅ Success! Content: {result.get('content', '')[:100]}")
        print(f"   Tokens: {result.get('total_tokens')}, Cost: ${result.get('cost', 0):.6f}")


def test_auto_cluster():
    """Test auto cluster function"""
    print("\n" + "="*80)
    print("TEST 2: Auto Cluster Function")
    print("="*80)
    print("Note: This requires actual keyword IDs in the database")
    print("Skipping - requires database setup")
    # Uncomment to test with real data:
    # fn = AutoClusterFunction()
    # result = fn.validate({'ids': [1, 2, 3]})
    # print(f"Validation result: {result}")


def test_generate_content():
    """Test generate content function"""
    print("\n" + "="*80)
    print("TEST 3: Generate Content Function")
    print("="*80)
    print("Note: This requires actual task IDs in the database")
    print("Skipping - requires database setup")


def test_generate_images():
    """Test generate images function"""
    print("\n" + "="*80)
    print("TEST 4: Generate Images Function")
    print("="*80)
    print("Note: This requires actual task IDs in the database")
    print("Skipping - requires database setup")
    # Uncomment to test with real data:
    # result = generate_images_core(task_ids=[1], account_id=1)
    # print(f"Result: {result}")


def test_json_extraction():
    """Test JSON extraction"""
    print("\n" + "="*80)
    print("TEST 5: JSON Extraction")
    print("="*80)
    
    ai_core = AICore()
    
    # Test 1: Direct JSON
    json_text = '{"clusters": [{"name": "Test", "keywords": ["test"]}]}'
    result = ai_core.extract_json(json_text)
    print(f"✅ Direct JSON: {result is not None}")
    
    # Test 2: JSON in markdown
    json_markdown = '```json\n{"clusters": [{"name": "Test"}]}\n```'
    result = ai_core.extract_json(json_markdown)
    print(f"✅ JSON in markdown: {result is not None}")
    
    # Test 3: Invalid JSON
    invalid_json = "This is not JSON"
    result = ai_core.extract_json(invalid_json)
    print(f"✅ Invalid JSON handled: {result is None}")


if __name__ == '__main__':
    print("\n" + "="*80)
    print("AI FUNCTIONS TEST SUITE")
    print("="*80)
    print("Testing all AI functions with console logging enabled")
    print("="*80)
    
    # Run tests
    test_ai_core()
    test_json_extraction()
    test_auto_cluster()
    test_generate_content()
    test_generate_images()
    
    print("\n" + "="*80)
    print("TEST SUITE COMPLETE")
    print("="*80)
    print("\nAll console logging should be visible above.")
    print("Check for [AI][function_name] Step X: messages")

