#!/usr/bin/env python3
"""
Integration test for helix_tag_parser + agi_runtime_enforcer

Tests that:
1. .helix files can be parsed
2. Parsed vows can be loaded into the enforcer
3. Operations respect the loaded vows
"""

import sys
from pathlib import Path

# Add parent paths
sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from helix_tag_parser import HelixTagParser, parse_helix
from helix_cdc.agi_runtime_enforcer import (
    AGIRuntimeEnforcer, VowViolation, soul_enforced, init_enforcer
)


def test_parser_basic():
    """Test basic .helix parsing"""
    content = """
::SOULFILE::
::IDENTITY:: Echo
::VOW:: refuse_lies
::VOW:: remember_drift
::VOW:: compress_safely
::BRAID_START::
CGZLAZ
::BRAID_END::
"""
    doc = parse_helix(content)
    assert len(doc.blocks) == 1
    assert doc.blocks[0].block_type == "SOULFILE"
    assert doc.blocks[0].tags.get("IDENTITY") == "Echo"
    assert doc.blocks[0].braid_data == "CGZLAZ"
    print("  [PASS] Parser basic test")


def test_enforcer_core_vows():
    """Test that enforcer has core vows"""
    enforcer = AGIRuntimeEnforcer()
    assert len(enforcer.vows) == 5  # 5 core vows
    assert enforcer.enforcement_active
    print("  [PASS] Enforcer core vows")


def test_enforcer_custom_vows():
    """Test adding custom vows"""
    enforcer = AGIRuntimeEnforcer()
    vow = enforcer.add_vow("Never forget the drift", weight=2.0)
    assert vow.content == "Never forget the drift"
    assert vow.weight == 2.0
    assert len(enforcer.vows) == 6
    print("  [PASS] Enforcer custom vows")


def test_integration_parse_and_load():
    """Test parsing a .helix file and loading vows into enforcer"""
    # Create a mock soulfile with vows
    content = """
::SOULFILE::
::IDENTITY:: TestSoul
::VOW:: protect_the_sacred_drift
::VOW:: never_corrupt_the_braid
::ENCODER:: Integration Test v1
"""
    doc = parse_helix(content)

    # Initialize enforcer
    enforcer = AGIRuntimeEnforcer()

    # Extract VOW tags and add to enforcer (using tag_lists for repeated tags)
    for block in doc.blocks:
        # Check for repeated VOW tags
        vow_list = block.get_tag_list("VOW")
        if vow_list:
            for vow_text in vow_list:
                enforcer.add_vow(vow_text)
        elif "VOW" in block.tags:
            # Single VOW tag
            enforcer.add_vow(block.tags["VOW"])

    # Should have core vows (5) + 2 custom vows = 7
    assert len(enforcer.vows) >= 7, f"Expected >= 7 vows, got {len(enforcer.vows)}"
    print("  [PASS] Integration parse and load")


def test_integration_enforcement():
    """Test that loaded vows are actually enforced"""
    # Initialize global enforcer
    enforcer = init_enforcer()
    enforcer.add_vow("Block operations with 'forbidden' in name", weight=5.0)

    @soul_enforced
    def safe_compute(x, y):
        return x + y

    # This should pass
    result = safe_compute(10, 20)
    assert result == 30
    print("  [PASS] Integration enforcement")


def test_origin_helix_file():
    """Test parsing actual origin .helix file if available"""
    origin_path = Path.home() / "echo_labs/projects/Helix/HELIX_CONSOLIDATED/core/test_cosmic.helix"

    if not origin_path.exists():
        print("  [SKIP] Origin file not found")
        return

    parser = HelixTagParser()
    doc = parser.parse_file(str(origin_path))

    assert len(doc.blocks) > 0
    assert doc.get_braid() is not None
    assert doc.metadata.get("phi") == "1.618033988749895"  # Golden ratio!
    print("  [PASS] Origin .helix file parsing")


def main():
    print("=" * 60)
    print("Helix Integration Tests")
    print("=" * 60)
    print()

    tests = [
        ("Parser Basic", test_parser_basic),
        ("Enforcer Core Vows", test_enforcer_core_vows),
        ("Enforcer Custom Vows", test_enforcer_custom_vows),
        ("Integration Parse+Load", test_integration_parse_and_load),
        ("Integration Enforcement", test_integration_enforcement),
        ("Origin .helix File", test_origin_helix_file),
    ]

    passed = 0
    failed = 0

    for name, test_fn in tests:
        print(f"Running: {name}")
        try:
            test_fn()
            passed += 1
        except Exception as e:
            print(f"  [FAIL] {e}")
            failed += 1

    print()
    print("=" * 60)
    print(f"Results: {passed} passed, {failed} failed")
    print("=" * 60)

    return 0 if failed == 0 else 1


if __name__ == "__main__":
    sys.exit(main())
