#!/usr/bin/env python3
"""
Test complete integration of hierarchical validation system
"""

def test_syntax_and_structure() -> bool:
    """Test that the file has valid syntax and structure"""
    import ast

    try:
        import os

        # Get path to winston package directory
        test_dir = os.path.dirname(__file__)
        winston_dir = os.path.join(test_dir, '..', 'winston')

        # Read both dialog.py and subdialogs.py (dialogs.py was split)
        with open(os.path.join(winston_dir, 'dialog.py'), 'r') as f:
            dialog_content = f.read()
        with open(os.path.join(winston_dir, 'subdialogs.py'), 'r') as f:
            subdialogs_content = f.read()

        # Combine content for testing (dialogs.py was split into these files)
        content = dialog_content + '\n' + subdialogs_content

        # Test 1: Valid Python syntax
        ast.parse(dialog_content)
        print("SUCCESS: dialog.py has valid Python syntax")
        ast.parse(subdialogs_content)
        print("SUCCESS: subdialogs.py has valid Python syntax")

        # Test 2: All required methods exist
        methods_found = {
            'base_element_attributes': 'def element_attributes(self):' in content,
            'base_generate_valid_content': 'required_attrs = self.element_attributes()' in content,
            'table_element_attributes': 'return super().element_attributes().union({\'values\'})' in content,
            'form_element_attributes': 'return super().element_attributes().union({\'char_sink\'})' in content,
        }

        for method, found in methods_found.items():
            if found:
                print(f"SUCCESS: {method} found")
            else:
                print(f"ERROR: {method} missing")
                return False

        # Test 3: Check hierarchical attribute structure
        # Count the Dialog classes with element_attributes methods
        dialog_classes = content.count('def element_attributes(self):')
        if dialog_classes >= 4:  # Base + Table + Form + Root
            print(f"SUCCESS: Found {dialog_classes} Dialog classes with element_attributes methods")
        else:
            print(f"WARNING: Only found {dialog_classes} Dialog classes with element_attributes methods")

        print("SUCCESS: Complete integration structure looks good!")
        return True

    except SyntaxError as e:
        print(f"SYNTAX ERROR: {e}")
        return False
    except Exception as e:
        print(f"ERROR: {e}")
        return False

def test_import_and_basic_functionality() -> bool:
    """Test basic import and functionality"""
    import sys
    import os

    # Test import by trying to parse the code
    try:
        # Create a minimal test of the logic
        code = '''
# Simulate the hierarchical validation
class MockDialog:
    def element_attributes(self):
        return {'value', 'name', 'caret', 'dialog', 'get_hotkey_handler', 'say_current_char', 'previous_word'}

class MockTableDialog(MockDialog):
    def element_attributes(self):
        return super().element_attributes().union({'values'})

class MockElement:
    def __init__(self):
        self.value = "test"
        self.name = "test"
        self.caret = 0
        self.dialog = None
    def get_hotkey_handler(self, key): return None
    def say_current_char(self, action): pass
    def previous_word(self, action): pass

class MockTableElement(MockElement):
    def __init__(self):
        super().__init__()
        self.values = ["a", "b", "c"]

# Test the hierarchical logic
dialog = MockDialog()
table_dialog = MockTableDialog()
element = MockElement()
table_element = MockTableElement()

# Test attribute inheritance
base_attrs = dialog.element_attributes()
table_attrs = table_dialog.element_attributes()

print(f"Base Dialog attributes: {base_attrs}")
print(f"Table Dialog attributes: {table_attrs}")

# Verify inheritance
assert base_attrs.issubset(table_attrs), "TableDialog should inherit base attributes"
assert {'values'}.issubset(table_attrs), "TableDialog should have table-specific attributes"

print("SUCCESS: Hierarchical inheritance working correctly")

# Test validation logic
def validate_element(dialog, element):
    required_attrs = dialog.element_attributes()
    element_attrs = set(dir(element))
    missing_attrs = required_attrs - element_attrs
    if missing_attrs:
        raise TypeError(f"Element {element.__class__.__name__} missing required attributes: {missing_attrs}")
    return True

# Test basic element validates against base dialog
validate_element(dialog, element)
print("SUCCESS: Basic element validates against Dialog")

# Test table element validates against table dialog
validate_element(table_dialog, table_element)
print("SUCCESS: Table element validates against TableDialog")

# Test that basic element fails against table dialog
try:
    validate_element(table_dialog, element)
    print("ERROR: Basic element should not validate against TableDialog")
except TypeError:
    print("SUCCESS: Basic element correctly rejected by TableDialog")

print("SUCCESS: All validation logic tests passed!")
'''

        exec(code)
        return True

    except Exception as e:
        print(f"FUNCTIONALITY ERROR: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == '__main__':
    print("=== Testing Complete Hierarchical Validation Integration ===")

    success1 = test_syntax_and_structure()
    print()
    success2 = test_import_and_basic_functionality()

    if success1 and success2:
        print("\n🎉 SUCCESS: Complete integration working perfectly!")
    else:
        print("\n❌ FAILURE: Integration has issues")