#!/usr/bin/env python3
"""
Test the actual auto_summarize function with a real long history.

This test creates a long history that would trigger the IterationSummarizerAgent
and tests if the cleansing logic prevents uni-api 400 errors with dangling tool_calls.
"""

import asyncio
import sys
sys.path.insert(0, '/home/GOD/heaven-framework-repo')

from heaven_base.utils.auto_summarize import auto_summarize
from heaven_base.memory.history import History
from heaven_base.utils.token_counter import count_tokens
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage


def create_long_test_history(target_iterations: int = 51) -> History:
    """Create a history with many iterations to trigger real summarization."""
    
    print(f"Creating test history with {target_iterations} iterations...")
    
    # Start with system message
    messages = [
        SystemMessage(content="You are a helpful coding assistant working on a complex project.")
    ]
    
    # Add many user-assistant pairs (iterations)
    for i in range(target_iterations):
        # User message
        user_content = f"""Iteration {i+1}: I need help with implementing feature #{i+1}. 
        This is a complex multi-step process that involves:
        - Analyzing the current codebase structure
        - Identifying the optimal integration points  
        - Writing comprehensive tests
        - Implementing the feature with proper error handling
        - Updating documentation and examples
        
        Please provide detailed guidance on how to approach this systematically.
        Make sure to consider edge cases and performance implications.
        """
        
        # AI response
        ai_content = f"""For iteration {i+1}, I'll help you implement feature #{i+1}. Here's my systematic approach:

        **Analysis Phase:**
        1. First, let me examine the existing codebase structure to understand the current architecture
        2. I'll identify the key integration points where this feature should connect
        3. We need to analyze dependencies and potential conflicts with existing functionality
        
        **Implementation Strategy:**
        1. Start with comprehensive unit tests to define the expected behavior
        2. Implement the core functionality using established patterns in your codebase
        3. Add proper error handling and validation
        4. Integrate with existing logging and monitoring systems
        
        **Testing & Validation:**
        1. Run the test suite to ensure no regressions
        2. Test edge cases and error conditions
        3. Performance testing to ensure acceptable response times
        4. Integration testing with dependent systems
        
        **Documentation:**
        1. Update API documentation with new endpoints/methods
        2. Add usage examples and best practices
        3. Update changelog and migration guides if needed
        
        This systematic approach for feature #{i+1} will ensure robust implementation. Let me know if you'd like me to dive deeper into any specific aspect.
        """
        
        messages.append(HumanMessage(content=user_content))
        messages.append(AIMessage(content=ai_content))
    
    # Create history
    history = History(messages=messages)
    
    # Calculate total tokens
    total_tokens = sum(count_tokens(msg.content, "gpt-4o-mini") for msg in messages)
    
    print(f"Created history with:")
    print(f"  - {len(messages)} messages")
    print(f"  - {target_iterations} iterations") 
    print(f"  - ~{total_tokens:,} tokens")
    print(f"  - Should trigger IterationSummarizerAgent")
    
    return history


async def test_real_auto_summarize():
    """Test the actual auto_summarize function that we've been working on."""
    
    print("=== Testing Real auto_summarize Function ===\n")
    
    # Create a long history that will definitely need summarization
    history = create_long_test_history(51)
    
    # Save the history so it has an ID
    history_id = history.save("test_real_auto_summarize")
    print(f"Saved history with ID: {history_id}")
    
    print(f"\n--- Running auto_summarize on {history_id} ---")
    print("This should:")
    print("  1. Create IterationSummarizerAgent") 
    print("  2. Use ViewHistoryTool to read all 51 iterations")
    print("  3. Call IterationSummarizerTool for each iteration")
    print("  4. Use uni-api for all LLM calls")
    print("  5. Test the cleansing logic for dangling tool_calls")
    print()
    
    try:
        # Call the actual auto_summarize function we've been working on
        result = await auto_summarize(history_id)
        
        print("✅ auto_summarize completed successfully!")
        print(f"Result type: {type(result)}")
        
        if isinstance(result, dict):
            print(f"Result keys: {list(result.keys())}")
            
            # Check iteration summaries
            iteration_summaries = result.get("iteration_summaries", [])
            print(f"Iteration summaries created: {len(iteration_summaries)}")
            
            if len(iteration_summaries) > 0:
                print(f"First summary preview: {iteration_summaries[0][:100]}...")
                
            # Check if we got all 51 iterations
            if len(iteration_summaries) == 51:
                print("🎉 SUCCESS: All 51 iterations were summarized!")
                print("This means the IterationSummarizerAgent successfully:")
                print("  - Read all iterations using ViewHistoryTool")
                print("  - Created summaries using IterationSummarizerTool") 
                print("  - Made uni-api calls without 400 errors")
                print("  - The cleansing logic prevented dangling tool_calls!")
            elif len(iteration_summaries) > 0:
                print(f"⚠️  Only {len(iteration_summaries)} iterations summarized out of 51")
                print("The agent may have stopped early or hit iteration limits")
            else:
                print("❌ No iteration summaries created")
                
            # Check aggregated summary
            if result.get("aggregated_summary"):
                print(f"✅ Aggregated summary created: {len(result['aggregated_summary'])} chars")
            else:
                print("⚠️  No aggregated summary created")
                
        else:
            print(f"Result: {result}")
            
        return result
        
    except Exception as e:
        print(f"❌ auto_summarize failed: {type(e).__name__}: {e}")
        print("This could indicate:")
        print("  - uni-api 400 errors from dangling tool_calls (cleansing not working)")
        print("  - IterationSummarizerAgent configuration issues")
        print("  - ViewHistoryTool or IterationSummarizerTool problems")
        
        # Print more debug info
        import traceback
        print(f"\nFull traceback:")
        traceback.print_exc()
        
        return None


async def main():
    """Run the real auto_summarize test."""
    print("🧪 Testing Real auto_summarize Function (with cleansing fix)")
    print("=" * 60)
    
    result = await test_real_auto_summarize()
    
    print(f"\n" + "=" * 60)
    if result:
        print("🎉 TEST PASSED: auto_summarize worked without uni-api errors!")
        print("The cleansing logic is successfully preventing 400 errors.")
    else:
        print("❌ TEST FAILED: auto_summarize had errors")
        print("The cleansing logic may not be working correctly.")


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