#!/usr/bin/env python3
"""
Test placeholder resolution in inline templates

This script simulates what happens in workflow_executor.load_prompt_template()
"""
import sys
sys.path.insert(0, 'backend')

from placeholder_resolver import get_placeholder_example_values, get_placeholder_catalog
from prompt_executor import resolve_placeholders

# Test profile_id (use first profile in dev DB)
PROFILE_ID = "019601b5-d65a-738f-a1e7-b3f69bb97f69"  # Lars profile from dev

def test_placeholder_resolution():
    """Test the exact same logic as in workflow_executor.load_prompt_template()"""

    # Test template with spaces in placeholders (as user showed)
    template = "Hallo {{ name }}, du bist {{ age }} Jahre alt und {{ geschlecht }}."

    print("=" * 80)
    print("PLACEHOLDER RESOLUTION TEST")
    print("=" * 80)
    print(f"\nTemplate:\n{template}\n")

    # Step 1: Load placeholders (same as workflow_executor)
    print("Step 1: Loading placeholders...")
    processed_placeholders = get_placeholder_example_values(PROFILE_ID)
    print(f"  Loaded {len(processed_placeholders)} placeholders")
    print(f"  Sample keys (first 5): {list(processed_placeholders.keys())[:5]}")

    # Step 2: Clean keys (same as workflow_executor)
    print("\nStep 2: Cleaning keys...")
    cleaned_placeholders = {
        key.replace('{{', '').replace('}}', '').strip(): value
        for key, value in processed_placeholders.items()
    }
    print(f"  Cleaned keys (first 5): {list(cleaned_placeholders.keys())[:5]}")
    print(f"  Sample values:")
    print(f"    name = {cleaned_placeholders.get('name')}")
    print(f"    age = {cleaned_placeholders.get('age')}")
    print(f"    geschlecht = {cleaned_placeholders.get('geschlecht')}")

    variables = cleaned_placeholders

    # Step 3: Load catalog
    print("\nStep 3: Loading catalog...")
    try:
        catalog = get_placeholder_catalog(PROFILE_ID)
        print(f"  Catalog loaded with {len(catalog)} categories")
    except Exception as e:
        catalog = None
        print(f"  Catalog failed: {e}")

    # Step 4: Resolve placeholders
    print("\nStep 4: Resolving placeholders...")
    debug_info = {}
    resolved = resolve_placeholders(
        template=template,
        variables=variables,
        debug_info=debug_info,
        catalog=catalog
    )

    print(f"  Resolved placeholders: {debug_info.get('resolved_placeholders', {})}")
    print(f"  Unresolved placeholders: {debug_info.get('unresolved_placeholders', [])}")

    # Result
    print("\n" + "=" * 80)
    print("RESULT")
    print("=" * 80)
    print(f"\nResolved template:\n{resolved}\n")

    # Check if placeholders were resolved
    if '{{' in resolved:
        print("❌ FAILED: Some placeholders were not resolved!")
        return False
    else:
        print("✅ SUCCESS: All placeholders resolved!")
        return True

if __name__ == "__main__":
    success = test_placeholder_resolution()
    sys.exit(0 if success else 1)
