#!/usr/bin/env python3
"""Test script to verify styrene-cleave package integration.

This script tests the key integration points used by P.I.G. Farm:
- assess_directive: Complexity assessment
- init_workspace: Workspace initialization
- reunify_workspace: Task reunification
"""

from pathlib import Path
from tempfile import TemporaryDirectory


def test_imports():
    """Test that all required imports are available."""
    print("Testing imports from styrene-cleave package...")

    try:
        from cleave import (
            AssessmentResult,
            assess_directive,
            check_missing_permissions,
            detect_conflicts,
            infer_permissions,
            init_workspace,
            match_pattern,
            reunify_workspace,
        )
        print("✓ All imports successful")
        return True
    except ImportError as e:
        print(f"✗ Import failed: {e}")
        return False


def test_assess_directive():
    """Test offline directive assessment."""
    print("\nTesting assess_directive...")

    try:
        from cleave import assess_directive

        # Simple directive
        result = assess_directive("Add a new user table to the database")
        print(f"  Simple directive: decision={result.decision}, complexity={result.complexity:.2f}")

        # Complex directive
        result = assess_directive(
            "Refactor the authentication system, update the API endpoints, "
            "migrate the database schema, and update all documentation"
        )
        print(f"  Complex directive: decision={result.decision}, complexity={result.complexity:.2f}")

        print("✓ assess_directive working")
        return True
    except Exception as e:
        print(f"✗ assess_directive failed: {e}")
        return False


def test_init_workspace():
    """Test workspace initialization."""
    print("\nTesting init_workspace...")

    try:
        from cleave import init_workspace

        with TemporaryDirectory() as tmpdir:
            workspace_path = Path(tmpdir) / ".cleave"

            # Initialize workspace with test tasks
            result = init_workspace(
                directive="Test multi-step task",
                children=["Step 1: Setup", "Step 2: Execute", "Step 3: Verify"],
                output_dir=str(workspace_path)
            )

            print(f"  Workspace created: {result['workspace_path']}")
            print(f"  Task count: {result['task_count']}")
            print(f"  Manifest exists: {result['has_manifest']}")

            # Verify workspace structure
            assert workspace_path.exists(), "Workspace directory not created"
            assert (workspace_path / "manifest.yaml").exists(), "Manifest not created"
            assert result['task_count'] == 3, f"Expected 3 tasks, got {result['task_count']}"

            print("✓ init_workspace working")
            return True
    except Exception as e:
        print(f"✗ init_workspace failed: {e}")
        return False


def test_reunify_workspace():
    """Test workspace reunification."""
    print("\nTesting reunify_workspace...")

    try:
        from cleave import init_workspace, reunify_workspace

        with TemporaryDirectory() as tmpdir:
            workspace_path = Path(tmpdir) / ".cleave"

            # Create a workspace
            init_workspace(
                directive="Test reunification",
                children=["Task 1", "Task 2"],
                output_dir=str(workspace_path)
            )

            # Reunify (will have pending tasks since we haven't executed)
            result = reunify_workspace(str(workspace_path))

            print(f"  Rollup status: {result['rollup_status']}")
            print(f"  Task count: {result['task_count']}")
            print(f"  Conflicts found: {result['conflicts_found']}")

            print("✓ reunify_workspace working")
            return True
    except Exception as e:
        print(f"✗ reunify_workspace failed: {e}")
        return False


def test_pattern_matching():
    """Test pattern matching for known directives."""
    print("\nTesting pattern matching...")

    try:
        from cleave import match_pattern

        # Test a commit directive (should match pattern)
        result = match_pattern("commit the changes")
        if result:
            print(f"  Matched pattern: {result.pattern_id} (confidence: {result.confidence:.2f})")
        else:
            print("  No pattern matched for commit directive")

        # Test a generic directive
        result = match_pattern("write a complex distributed system")
        if result:
            print(f"  Matched pattern: {result.pattern_id} (confidence: {result.confidence:.2f})")
        else:
            print("  No pattern matched for generic directive")

        print("✓ match_pattern working")
        return True
    except Exception as e:
        print(f"✗ match_pattern failed: {e}")
        return False


def test_integration_layer():
    """Test the pigfarm integration layer functions."""
    print("\nTesting integration layer functions...")

    try:
        from pigfarm.services.cleave_integration import (
            assess_offline,
            check_permissions_for_directive,
            get_suggested_children,
            watch_workspace_status,
        )

        # Test assess_offline with different thresholds
        result = assess_offline("Simple task", threshold=2.0)
        print(f"  assess_offline: decision={result['decision']}, tier={result['tier']}")
        assert "complexity" in result
        assert "decision" in result
        assert result["tier"] in [0, 1, 2]

        # Test check_permissions_for_directive
        result = check_permissions_for_directive("commit the changes")
        print(f"  check_permissions: all_covered={result['all_covered']}, missing={len(result['missing'])}")
        assert "all_covered" in result
        assert "missing" in result

        # Test get_suggested_children
        result = get_suggested_children("commit the changes")
        print(f"  get_suggested_children: {len(result)} suggestions")
        assert isinstance(result, list)

        # Test watch_workspace_status with non-existent workspace
        result = watch_workspace_status("/tmp/nonexistent/.cleave")
        print(f"  watch_workspace_status (nonexistent): exists={result['exists']}")
        assert result["exists"] is False

        print("✓ integration layer working")
        return True
    except Exception as e:
        print(f"✗ integration layer failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_error_handling():
    """Test error handling and edge cases."""
    print("\nTesting error handling...")

    try:
        from cleave import assess_directive, match_pattern

        # Test empty directive
        result = assess_directive("")
        print(f"  Empty directive: decision={result.decision}")

        # Test very long directive
        long_directive = "do task " * 100
        result = assess_directive(long_directive)
        print(f"  Long directive: complexity={result.complexity:.2f}")

        # Test special characters
        result = assess_directive("Fix bug in $HOME/config.yaml & restart service")
        print(f"  Special chars: decision={result.decision}")

        # Test pattern matching with no match
        result = match_pattern("xyzabc123")
        if result:
            print(f"  Random string matched: {result.pattern_id}")
        else:
            print("  Random string: no match (expected)")

        print("✓ error handling working")
        return True
    except Exception as e:
        print(f"✗ error handling failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """Run all integration tests."""
    print("=" * 60)
    print("styrene-cleave Integration Test")
    print("=" * 60)

    tests = [
        test_imports,
        test_assess_directive,
        test_init_workspace,
        test_reunify_workspace,
        test_pattern_matching,
        test_integration_layer,
        test_error_handling,
    ]

    results = [test() for test in tests]

    print("\n" + "=" * 60)
    passed = sum(results)
    total = len(results)
    print(f"Results: {passed}/{total} tests passed")

    if all(results):
        print("✓ All integration tests passed")
        print("\nThe styrene-cleave package is properly integrated.")
        return 0
    else:
        print("✗ Some integration tests failed")
        print("\nThe package may not be installed or has breaking changes.")
        return 1


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