"""Test execution orchestrator - end-to-end flow."""

import sys
import tempfile
from pathlib import Path

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

from unishell.core.intent import LLMIntentClassifier, LLMParameterExtractor
from unishell.core.action_registry import ActionRegistryImpl
from unishell.core.policy_engine import SimplePolicyEngine
from unishell.core.rollback import SimpleRollbackManager
from unishell.core.execution import SafeOSExecutionAdapter
from unishell.core.monitoring import SimpleMonitoringEngine
from unishell.core.gateway import ExecutionOrchestrator

print("=== Execution Orchestrator Tests ===\n")

# Initialize all components
classifier = LLMIntentClassifier(llm_client=None, confidence_threshold=0.7)
extractor = LLMParameterExtractor(llm_client=None, confidence_threshold=0.7)
registry = ActionRegistryImpl()
policy = SimplePolicyEngine(user_role="user", environment="development")
rollback = SimpleRollbackManager()
adapter = SafeOSExecutionAdapter()
monitor = SimpleMonitoringEngine()

# Load actions
actions_dir = Path(__file__).parent.parent / "unishell" / "core" / "action_registry" / "actions"
for file in actions_dir.glob("*.json"):
    registry.load_from_file(str(file))

# Create orchestrator
orchestrator = ExecutionOrchestrator(
    classifier, extractor, registry, policy, rollback, adapter, monitor
)

print("=== Test 1: Successful Execution (Dry Run) ===")
result = orchestrator.execute("Move file from /tmp/test.txt to /tmp/moved.txt", dry_run=True)
print(f"Success: {result['success']}")
print(f"Stage: {result['stage']}")
print(f"Message: {result['message']}")
print(f"Dry Run: {result.get('dry_run')}")
print()

print("=== Test 2: Real Execution with Rollback ===")
with tempfile.TemporaryDirectory() as tmpdir:
    tmpdir = Path(tmpdir)
    test_file = tmpdir / "test.txt"
    test_file.write_text("Test content")
    
    # Execute move
    result = orchestrator.execute(
        f"Move file from {test_file} to {tmpdir / 'moved.txt'}",
        dry_run=False
    )
    print(f"Success: {result['success']}")
    print(f"Message: {result['message']}")
    print(f"File moved: {(tmpdir / 'moved.txt').exists()}")
    print()

print("=== Test 3: Policy Denial ===")
result = orchestrator.execute("Restart the system", dry_run=True)
print(f"Success: {result['success']}")
print(f"Stage: {result['stage']}")
print(f"Message: {result['message']}")
print()

print("=== Test 4: Missing Parameters ===")
result = orchestrator.execute("Move something", dry_run=True)
print(f"Success: {result['success']}")
print(f"Stage: {result['stage']}")
print(f"Message: {result['message']}")
print()

print("=== Test 5: Unclear Intent ===")
result = orchestrator.execute("Do something unclear", dry_run=True)
print(f"Success: {result['success']}")
print(f"Stage: {result['stage']}")
print(f"Message: {result['message']}")
print()

print("=== Test 6: Monitoring Statistics ===")
stats = monitor.get_statistics()
print(f"Total events: {stats['total_events']}")
print(f"Started: {stats['started']}")
print(f"Success: {stats['success']}")
print(f"Failed: {stats['failed']}")
print(f"Success rate: {stats['success_rate']:.2%}")
print()

print("=== Test 7: Recent Events ===")
recent = monitor.get_recent_events(limit=5)
print(f"Recent events:")
for log in recent:
    print(f"  - {log.action_id}: {log.status}")
print()

print("=== Test 8: Rollback Snapshots ===")
snapshots = rollback.list_snapshots()
print(f"Total snapshots: {len(snapshots)}")
for snap in snapshots:
    print(f"  - {snap.action_id}: committed={snap.committed}")
print()

print("[SUCCESS] Execution orchestrator tests complete!")
