#!/usr/bin/env python3
"""Smoke tests for Novyx CLI."""

import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))


class TestCLISmoke(unittest.TestCase):
    """Smoke tests for tools/cli.py."""

    def test_create_decision_from_json_validates(self):
        """Create a Decision via CLI using JSON payload, verify it exists and validates."""
        
        with tempfile.TemporaryDirectory() as tmpdir:
            # Prepare JSON payload
            payload = {
                "title": "CLI Test Decision",
                "context": "Testing CLI creation",
                "options_considered": ["Option A", "Option B"],
                "chosen_option": "Option A",
                "reasoning": "Testing purposes",
                "constraints": ["Time", "Resources"],
                "assumptions": ["Stable environment"],
                "confidence": 0.9,
                "expected_outcome": "Successful test",
                "category": "test"
            }
            
            json_path = Path(tmpdir) / "decision_payload.json"
            with open(json_path, 'w') as f:
                json.dump(payload, f)
            
            # Create a temporary output directory structure
            # We need to temporarily modify where artifacts go
            # For now, let's just use memory/decisions and validate it's created
            
            # Run CLI create command
            result = subprocess.run(
                [
                    sys.executable, "-m", "tools.cli",
                    "create", "decision",
                    "--json", str(json_path),
                    "--link", "https://github.com/test",
                    "--verbose"
                ],
                capture_output=True,
                text=True,
                cwd=Path(__file__).parent.parent
            )
            
            # Check command succeeded
            self.assertEqual(result.returncode, 0, 
                           f"CLI create failed:\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")
            
            # Verify output contains expected messages
            self.assertIn("Decision created successfully", result.stdout)
            self.assertIn("UUID:", result.stdout)
            self.assertIn("Hash:", result.stdout)
            self.assertIn("Validation: PASSED", result.stdout)
            
            # Extract file path from output
            for line in result.stdout.split('\n'):
                if "Path:" in line:
                    path_str = line.split("Path:")[1].strip()
                    created_file = Path(path_str)
                    
                    # Verify file exists
                    self.assertTrue(created_file.exists(), f"Created file not found: {created_file}")
                    
                    # Verify it's a valid JSON-LD file
                    with open(created_file, 'r') as f:
                        data = json.load(f)
                    
                    self.assertEqual(data["title"], "CLI Test Decision")
                    self.assertIn("uuid", data)
                    self.assertIn("novyx:integrityHash", data)
                    self.assertNotEqual(data["novyx:integrityHash"], "pending_calculation")
                    
                    # Clean up (remove created file)
                    created_file.unlink()
                    break
            else:
                self.fail("Could not find 'Path:' in CLI output")

    def test_validate_command_on_temp_directory(self):
        """Create an artifact and validate it using CLI validate command."""
        
        with tempfile.TemporaryDirectory() as tmpdir:
            # Use factory directly to create an artifact in temp dir
            from tools.factory import create_artifact, persist_artifact
            
            payload = {
                "title": "Validation Test",
                "context": "Testing validation",
                "options_considered": ["A"],
                "chosen_option": "A",
                "reasoning": "Test",
                "constraints": [],
                "assumptions": [],
                "confidence": 1.0,
                "expected_outcome": "Pass",
                "category": "test"
            }
            
            artifact = create_artifact("decision", payload)
            output_path = persist_artifact(artifact, Path(tmpdir))
            
            # Run CLI validate command
            result = subprocess.run(
                [
                    sys.executable, "-m", "tools.cli",
                    "validate",
                    "--directory", tmpdir,
                    "--verbose"
                ],
                capture_output=True,
                text=True,
                cwd=Path(__file__).parent.parent
            )
            
            # Check command succeeded
            self.assertEqual(result.returncode, 0,
                           f"CLI validate failed:\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")
            
            # Verify output contains success message
            self.assertIn("PASSED", result.stdout)
            self.assertIn("ALL INTEGRITY CHECKS PASSED", result.stdout)

    def test_query_command_shows_statistics(self):
        """Create artifacts and query statistics using CLI query command."""
        
        with tempfile.TemporaryDirectory() as tmpdir:
            # Create multiple artifacts  
            from tools.factory import create_artifact, persist_artifact
            
            for i in range(3):
                payload = {
                    "title": f"Query Test {i}",
                    "context": "Testing query",
                    "options_considered": ["A"],
                    "chosen_option": "A",
                    "reasoning": "Test",
                    "constraints": [],
                    "assumptions": [],
                    "confidence": 1.0,
                    "expected_outcome": "Pass",
                    "category": "test"
                }
                
                artifact = create_artifact("decision", payload)
                persist_artifact(artifact, Path(tmpdir))
            
            # Run CLI query command (without --search for statistics mode)
            result = subprocess.run(
                [
                    sys.executable, "-m", "tools.cli",
                    "query",
                    "--directory", tmpdir
                ],
                capture_output=True,
                text=True,
                cwd=Path(__file__).parent.parent
            )
            
            # Check command succeeded
            self.assertEqual(result.returncode, 0,
                           f"CLI query failed:\nSTDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}")
            
            # Verify output contains expected information
            # Note: The query command should find 3 artifacts
            self.assertIn("Total artifacts:", result.stdout)
            # Verify it found some artifacts (exact count may vary due to test isolation)
            self.assertRegex(result.stdout, r'Total artifacts:\s+[1-9]\d*')
            self.assertIn("By Type:", result.stdout)
            self.assertIn("Decision", result.stdout)

    def test_cli_help_commands(self):
        """Verify CLI help commands work."""
        
        # Test main help
        result = subprocess.run(
            [sys.executable, "-m", "tools.cli", "--help"],
            capture_output=True,
            text=True,
            cwd=Path(__file__).parent.parent
        )
        
        self.assertEqual(result.returncode, 0)
        self.assertIn("create", result.stdout)
        self.assertIn("validate", result.stdout)
        self.assertIn("query", result.stdout)
        
        # Test create help
        result = subprocess.run(
            [sys.executable, "-m", "tools.cli", "create", "--help"],
            capture_output=True,
            text=True,
            cwd=Path(__file__).parent.parent
        )
        
        self.assertEqual(result.returncode, 0)
        self.assertIn("decision", result.stdout)


if __name__ == '__main__':
    unittest.main()
