#!/usr/bin/env python3
"""
Test script to verify equation generation and system handling
"""

import json
import sys
import os
import requests
from datetime import datetime

# Add the project root to Python path
sys.path.insert(0, os.path.dirname(__file__))

def test_equation_generation():
    """Test that Grok4Fast generates correct equations and the system handles them properly"""

    print("🧪 TESTING EQUATION GENERATION & SYSTEM HANDLING")
    print("=" * 60)
    print()

    # Test 1: Check if Next.js server is running
    print("📡 Test 1: Checking server connectivity")
    base_url = "http://localhost:3000"

    # Try different ports
    for port in [3000, 3001, 3002, 3003]:
        try:
            response = requests.get(f"http://localhost:{port}/api/health", timeout=3)
            if response.status_code == 200:
                base_url = f"http://localhost:{port}"
                print(f"✅ Server is running on port {port}")
                break
        except:
            continue
    else:
        print("❌ Server not running on any port")
        return

    print()

    # Test 2: Test basic backtest with equation generation
    print("🎯 Test 2: Basic backtest with equation generation")

    test_queries = [
        "Backtest a simple trend following strategy on XAUUSD",
        "Test a mean reversion strategy on BTCUSD with 5-minute bars",
        "Create a breakout trading strategy for EURUSD",
        "Optimize momentum trading parameters for crypto"
    ]

    for i, query in enumerate(test_queries, 1):
        print(f"\n   Test 2.{i}: {query}")
        try:
            response = requests.post(
                f"{base_url}/api/chat",
                json={"message": query, "domain": "forex"},
                headers={"Content-Type": "application/json"},
                timeout=30
            )

            if response.status_code == 200:
                data = response.json()
                message = data.get('message', '')

                # Check for equation
                if 'Strategy Equation' in message or 'Equation:' in message:
                    print("   ✅ Equation generated and displayed")
                else:
                    print("   ⚠️  No equation found in response")

                # Check for backtest results
                if 'Key Performance Metrics' in message:
                    print("   ✅ Backtest results included")
                else:
                    print("   ⚠️  No backtest results found")

                # Check for memory context
                if 'memoryContext' in str(data):
                    print("   ✅ Memory system integrated")
                else:
                    print("   ⚠️  Memory context not found")

            else:
                print(f"   ❌ API error: {response.status_code} - {response.text[:100]}")

        except Exception as e:
            print(f"   ❌ Request failed: {str(e)}")

    print()

    # Test 3: Test memory integration
    print("🧠 Test 3: Memory system integration")

    try:
        # First message to establish memory
        response1 = requests.post(
            f"{base_url}/api/chat",
            json={"message": "I prefer forex trading and have medium risk tolerance", "domain": "forex"},
            headers={"Content-Type": "application/json"},
            timeout=15
        )

        if response1.status_code == 200:
            print("   ✅ First message processed")

            # Second message to test memory recall
            response2 = requests.post(
                f"{base_url}/api/chat",
                json={"message": "What strategy do you recommend for me?", "domain": "forex"},
                headers={"Content-Type": "application/json"},
                timeout=15
            )

            if response2.status_code == 200:
                data2 = response2.json()
                message2 = data2.get('message', '')

                # Check if memory influenced response
                memory_indicators = ['forex', 'medium risk', 'preference', 'experience']
                memory_found = any(indicator in message2.lower() for indicator in memory_indicators)

                if memory_found:
                    print("   ✅ Memory context influencing responses")
                else:
                    print("   ⚠️  Memory context may not be influencing responses")

                print("   ✅ Memory system responding")

    except Exception as e:
        print(f"   ❌ Memory test failed: {str(e)}")

    print()

    # Test 4: Test equation format validation
    print("📐 Test 4: Equation format validation")

    # Test various equation formats
    test_equations = [
        "If SMA(5) > SMA(20), BUY",
        "Price > Bollinger Upper Band",
        "RSI < 30 AND MACD > Signal",
        "Volume > Average Volume * 1.5",
        "Price breaks resistance level"
    ]

    print("   Validating equation formats:")
    for eq in test_equations:
        # Check if equation has logical structure
        has_condition = any(word in eq.upper() for word in ['IF', 'WHEN', '>', '<', 'AND', 'OR'])
        has_action = any(word in eq.upper() for word in ['BUY', 'SELL', 'ENTER', 'EXIT'])

        if has_condition and has_action:
            print(f"   ✅ '{eq}' - Valid format")
        else:
            print(f"   ⚠️  '{eq}' - Missing condition or action")

    print()

    # Test 5: Test error handling
    print("🚨 Test 5: Error handling and edge cases")

    error_queries = [
        "Backtest strategy with invalid parameters",
        "",
        "Test strategy that doesn't exist",
        "Optimize with negative numbers"
    ]

    for query in error_queries:
        if not query.strip():
            continue

        try:
            response = requests.post(
                f"{base_url}/api/chat",
                json={"message": query, "domain": "forex"},
                headers={"Content-Type": "application/json"},
                timeout=10
            )

            if response.status_code == 200:
                print(f"   ✅ Handled gracefully: '{query[:30]}...'")
            else:
                print(f"   ⚠️  Error response for: '{query[:30]}...' - {response.status_code}")

        except Exception as e:
            print(f"   ❌ Failed to handle: '{query[:30]}...' - {str(e)[:50]}")

    print()

    # Test 6: Performance test
    print("⚡ Test 6: Performance and response times")

    import time
    start_time = time.time()

    try:
        response = requests.post(
            f"{base_url}/api/chat",
            json={"message": "Backtest trend following on XAUUSD", "domain": "forex"},
            headers={"Content-Type": "application/json"},
            timeout=30
        )

        end_time = time.time()
        response_time = end_time - start_time

        if response.status_code == 200:
            if response_time < 10:
                print(f"   ✅ Fast response: {response_time:.1f}s")
            elif response_time < 20:
                print(f"   ⚠️  Acceptable response: {response_time:.1f}s")
            else:
                print(f"   ❌ Slow response: {response_time:.1f}s")
        else:
            print(f"   ❌ Performance test failed: {response.status_code}")

    except Exception as e:
        print(f"   ❌ Performance test failed: {str(e)}")

    print()

    # Summary
    print("📋 TEST SUMMARY")
    print("=" * 30)
    print("✅ System tested for:")
    print("   • Equation generation by Grok4Fast")
    print("   • Equation display in chat responses")
    print("   • Memory system integration")
    print("   • Error handling and edge cases")
    print("   • Performance and response times")
    print("   • Backtest result formatting")
    print()
    print("🎯 If any tests failed, check:")
    print("   • Grok4Fast API connectivity")
    print("   • Memory service configuration")
    print("   • Database connections")
    print("   • Error handling in chat routes")
    print()
    print("🚀 System ready for production testing!")

if __name__ == "__main__":
    test_equation_generation()
