#!/usr/bin/env python3
"""
Basic test of CSQL functionality without the full C++ build.
This tests the Python-only parts of the CSQL implementation.
"""

import sys
import os
import json

# Add the project root to the path so we can import cutysoup modules
sys.path.insert(0, '/home/ccuser/projects/CutySoupLearn')

# Test basic CSQL functionality
def test_csql_basic():
    """Test basic CSQL functionality."""
    print("Testing CSQL basic functionality...")
    
    try:
        from cutysoup.csql import CSQLEngine, CSQLQuery, CSQLError
        print("✓ Successfully imported CSQL modules")
        
        # Test with minimal HTML using BeautifulSoup4 as fallback
        try:
            from bs4 import BeautifulSoup
            print("✓ Using BeautifulSoup4 as HTML parser fallback")
            
            html = """
            <div class="test">
                <h1>Test Title</h1>
                <p class="content">Test content here</p>
                <a href="/test" class="link">Test Link</a>
            </div>
            """
            
            # Create a mock soup object that mimics CutySoup interface
            class MockSoup:
                def __init__(self, html):
                    self.bs = BeautifulSoup(html, 'html.parser')
                    
                def select(self, selector):
                    elements = self.bs.select(selector)
                    mock_elements = []
                    for elem in elements:
                        mock_elem = MockElement(elem)
                        mock_elements.append(mock_elem)
                    return mock_elements
                    
            class MockElement:
                def __init__(self, bs_element):
                    self.bs_element = bs_element
                    
                def get_text(self):
                    return self.bs_element.get_text().strip()
                    
                def get(self, attr):
                    return self.bs_element.get(attr)
                    
                def select(self, selector):
                    elements = self.bs_element.select(selector)
                    return [MockElement(elem) for elem in elements]
            
            mock_soup = MockSoup(html)
            
            # Test basic CSQL functionality
            engine = CSQLEngine(mock_soup)
            
            # Test simple text extraction
            plan = {
                "title": "h1"
            }
            
            result = engine.execute_query(plan)
            print(f"✓ Simple extraction result: {result}")
            
            # Test attribute extraction
            plan = {
                "link_url": {
                    "selector": "a.link",
                    "extract": "attribute",
                    "attribute": "href"
                }
            }
            
            result = engine.execute_query(plan)
            print(f"✓ Attribute extraction result: {result}")
            
            # Test list extraction
            plan = {
                "all_text": {
                    "selector": "h1, p",
                    "type": "list",
                    "extract": "text"
                }
            }
            
            result = engine.execute_query(plan)
            print(f"✓ List extraction result: {result}")
            
            print("✓ Basic CSQL functionality working correctly!")
            
        except ImportError:
            print("⚠ BeautifulSoup4 not available, skipping parser tests")
            
        # Test CSQL error handling
        print("\nTesting error handling...")
        
        # Test invalid JSON
        try:
            engine.execute_query('{"invalid": json}')
            print("✗ Should have raised CSQLError for invalid JSON")
        except CSQLError as e:
            print(f"✓ Correctly caught invalid JSON: {e}")
        
        # Test missing selector
        try:
            mock_soup = MockSoup("<div>test</div>")
            engine = CSQLEngine(mock_soup)
            engine.execute_query({"field": {"extract": "text"}})
            print("✗ Should have raised CSQLError for missing selector")
        except CSQLError as e:
            print(f"✓ Correctly caught missing selector: {e}")
            
        print("✓ Error handling working correctly!")
        
        return True
        
    except Exception as e:
        print(f"✗ CSQL test failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_transformations():
    """Test CSQL data transformations."""
    print("\nTesting data transformations...")
    
    try:
        from cutysoup.csql import CSQLEngine
        
        # Test transformation functions directly
        engine = CSQLEngine(None)
        
        # Test regex transformation
        result = engine._apply_single_transform("Price: $1,234.56", {"regex": r"[\d,.]+"})
        print(f"✓ Regex extraction: '{result}'")
        
        # Test replace transformation  
        result = engine._apply_single_transform("1,234", {"replace": {",": ""}})
        print(f"✓ Replace transformation: '{result}'")
        
        # Test strip transformation
        result = engine._apply_single_transform("  hello world  ", {"strip": True})
        print(f"✓ Strip transformation: '{result}'")
        
        # Test type casting
        result = engine._cast_value("123.45", "float")
        print(f"✓ Float casting: {result} (type: {type(result).__name__})")
        
        result = engine._cast_value("1,234", "integer")
        print(f"✓ Integer casting: {result} (type: {type(result).__name__})")
        
        result = engine._cast_value("true", "boolean")
        print(f"✓ Boolean casting: {result} (type: {type(result).__name__})")
        
        print("✓ Transformations working correctly!")
        return True
        
    except Exception as e:
        print(f"✗ Transformation test failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """Run all tests."""
    print("🔍 CSQL Basic Functionality Test")
    print("Testing Python-only parts of CSQL implementation")
    print("=" * 60)
    
    tests_passed = 0
    total_tests = 2
    
    if test_csql_basic():
        tests_passed += 1
        
    if test_transformations():
        tests_passed += 1
    
    print("\n" + "=" * 60)
    print(f"Test Results: {tests_passed}/{total_tests} passed")
    
    if tests_passed == total_tests:
        print("✅ All CSQL basic tests passed!")
        print("\n🚀 CSQL Phase 1 implementation is working correctly!")
        print("   Ready for integration with full CutySoup build.")
    else:
        print("❌ Some tests failed.")
        
    return tests_passed == total_tests


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