"""Complete integration test - All components working together."""

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.execution import SafeOSExecutionAdapter

print("=== Complete Integration Test ===\n")

# Initialize all components
print("Initializing 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")
adapter = SafeOSExecutionAdapter()

# 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))

print(f"Loaded {len(registry.list_actions())} actions\n")

# Test Case 1: Successful flow
print("=== Test Case 1: Successful File Move ===")
user_input = "Move file from /tmp/test.txt to /tmp/moved.txt"

# Step 1: Classify intent
intent_result = classifier.classify_sync(user_input)
print(f"1. Intent Classification:")
print(f"   Action ID: {intent_result.action_id}")
print(f"   Confidence: {intent_result.confidence}")

if intent_result.needs_clarification:
    print(f"   [STOP] {intent_result.reasoning}")
else:
    # Step 2: Get action from registry
    action = registry.get_action(intent_result.action_id)
    if not action:
        print(f"   [STOP] Unknown action")
    else:
        print(f"\n2. Action Registry:")
        print(f"   Action: {action.action_id}")
        print(f"   Risk: {action.risk_level}")
        print(f"   Permission: {action.permission_level}")
        
        # Step 3: Extract parameters
        param_result = extractor.extract_sync(
            user_input,
            intent_result.action_id,
            action.required_params
        )
        print(f"\n3. Parameter Extraction:")
        print(f"   Parameters: {param_result.parameters}")
        print(f"   Missing: {param_result.missing_fields}")
        
        if param_result.missing_fields:
            print(f"   [STOP] Missing fields")
        else:
            # Step 4: Policy evaluation
            policy_decision = policy.evaluate(action, param_result.parameters)
            print(f"\n4. Policy Evaluation:")
            print(f"   Allowed: {policy_decision.allowed}")
            print(f"   Reason: {policy_decision.reason}")
            
            if not policy_decision.allowed:
                print(f"   [STOP] Policy denied")
            else:
                # Step 5: Execute (dry run)
                with tempfile.TemporaryDirectory() as tmpdir:
                    tmpdir = Path(tmpdir)
                    test_file = tmpdir / "test.txt"
                    test_file.write_text("Test content")
                    
                    exec_result = adapter.move_file(
                        str(test_file),
                        str(tmpdir / "moved.txt"),
                        dry_run=True
                    )
                    print(f"\n5. Execution (Dry Run):")
                    print(f"   Success: {exec_result.success}")
                    print(f"   Message: {exec_result.message}")
                    print(f"   Dry Run: {exec_result.dry_run}")
                    
                    if exec_result.success:
                        print(f"\n[OK] Complete flow successful!")

print("\n" + "="*50 + "\n")

# Test Case 2: Permission denied
print("=== Test Case 2: Permission Denied ===")
user_input = "Restart the system"

intent_result = classifier.classify_sync(user_input)
print(f"1. Intent: {intent_result.action_id}")

action = registry.get_action(intent_result.action_id)
print(f"2. Action: {action.action_id} (requires: {action.permission_level})")

param_result = extractor.extract_sync(user_input, intent_result.action_id, action.required_params)
print(f"3. Parameters: {param_result.parameters}")

policy_decision = policy.evaluate(action, param_result.parameters)
print(f"4. Policy Decision:")
print(f"   Allowed: {policy_decision.allowed}")
print(f"   Reason: {policy_decision.reason}")

if not policy_decision.allowed:
    print(f"\n[OK] Correctly denied due to insufficient permissions")

print("\n" + "="*50 + "\n")

# Test Case 3: Missing parameters
print("=== Test Case 3: Missing Parameters ===")
user_input = "Delete something"

intent_result = classifier.classify_sync(user_input)
print(f"1. Intent: {intent_result.action_id}")

action = registry.get_action(intent_result.action_id)
if action:
    print(f"2. Action: {action.action_id}")
    
    param_result = extractor.extract_sync(user_input, intent_result.action_id, action.required_params)
    print(f"3. Parameters: {param_result.parameters}")
    print(f"   Missing: {param_result.missing_fields}")
    
    if param_result.missing_fields:
        print(f"\n[OK] Correctly identified missing parameters")

print("\n" + "="*50 + "\n")

# Test Case 4: Production environment with critical risk
print("=== Test Case 4: Critical Risk in Production ===")
policy_prod = SimplePolicyEngine(user_role="admin", environment="production")

user_input = "Restart the system"
intent_result = classifier.classify_sync(user_input)
action = registry.get_action(intent_result.action_id)
param_result = extractor.extract_sync(user_input, intent_result.action_id, action.required_params)

print(f"1. Action: {action.action_id} (risk: {action.risk_level})")
print(f"2. Environment: production")
print(f"3. User Role: admin")

policy_decision = policy_prod.evaluate(action, param_result.parameters)
print(f"4. Policy Decision:")
print(f"   Allowed: {policy_decision.allowed}")
print(f"   Reason: {policy_decision.reason}")

if not policy_decision.allowed:
    print(f"\n[OK] Correctly blocked critical risk in production")

print("\n[SUCCESS] Complete integration test passed!")
