#!/usr/bin/env python3
"""
Context Custodians - Basic Test Suite
Tests core functionality of the multi-agent system
"""

import os
import sys
import tempfile
import shutil
import unittest
from pathlib import Path

# Add the vmw package to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from vmw.core.config import ConfigManager
from vmw.core.state import StateManager
from vmw.agents.file_watcher import FileWatcherAgent
from vmw.agents.vital_extractor import VitalExtractorAgent
from vmw.agents.context_updater import ContextUpdaterAgent


class TestContextCustodians(unittest.TestCase):
    """Basic test suite for Context Custodians"""

    def setUp(self):
        """Set up test environment"""
        self.test_dir = tempfile.mkdtemp()
        self.config_path = os.path.join(self.test_dir, 'config.yaml')
        self.state_path = os.path.join(self.test_dir, 'state.json')

        # Create test config
        test_config = {
            'version': '0.1.0',
            'workspace': self.test_dir,
            'monitoring': {
                'enabled': True,
                'interval_seconds': 1,
                'watched_files': ['test_file.md'],
                'ignored_patterns': []
            },
            'agents': {
                'file_watcher': {'enabled': True},
                'vital_extractor': {'enabled': True},
                'context_updater': {'enabled': True}
            },
            'output': {
                'context_file': 'ALWAYS_AVAILABLE_CONTEXT.md',
                'vital_updates_file': 'VITAL_UPDATES.md'
            }
        }

        import yaml
        with open(self.config_path, 'w') as f:
            yaml.dump(test_config, f)

        # Initialize managers
        self.config = ConfigManager(self.config_path)
        self.state = StateManager(self.state_path)

    def tearDown(self):
        """Clean up test environment"""
        shutil.rmtree(self.test_dir)

    def test_config_loading(self):
        """Test configuration loading"""
        self.assertEqual(self.config.get('version'), '0.1.0')
        self.assertTrue(self.config.get('monitoring.enabled'))
        self.assertEqual(self.config.get('monitoring.interval_seconds'), 1)

    def test_state_management(self):
        """Test state persistence"""
        # Set some state
        self.state.set('test_key', 'test_value')
        self.state.set('file_hashes.test_file', 'abc123')

        # Reload state
        new_state = StateManager(self.state_path)
        self.assertEqual(new_state.get('test_key'), 'test_value')
        self.assertEqual(new_state.get('file_hashes.test_file'), 'abc123')

    def test_file_watcher_agent(self):
        """Test file watcher agent"""
        agent = FileWatcherAgent(self.config, self.state)

        # Create a test file
        test_file = os.path.join(self.test_dir, 'test_file.md')
        with open(test_file, 'w') as f:
            f.write('# Test File\n\nThis is a test file.')

        # Check if file is detected
        changed_files = agent.scan_for_changes()
        self.assertIn('test_file.md', changed_files)

        # Modify file
        with open(test_file, 'w') as f:
            f.write('# Modified Test File\n\nContent changed.')

        changed_files = agent.scan_for_changes()
        self.assertIn('test_file.md', changed_files)

    def test_vital_extractor_agent(self):
        """Test vital extractor agent"""
        agent = VitalExtractorAgent(self.config, self.state)

        # Create a test file with vital information
        test_file = os.path.join(self.test_dir, 'test_file.md')
        content = """
# Project Overview

This is a test project.

## Golden Rules

- Rule 1: Always test your code
- Rule 2: Document everything

## Configuration

```yaml
version: 1.0.0
setting: value
```
"""

        with open(test_file, 'w') as f:
            f.write(content)

        # Extract vital information
        vital_info = agent.extract_vital_info(test_file)

        self.assertIn('golden_rules', vital_info)
        self.assertIn('configuration', vital_info)
        self.assertEqual(len(vital_info['golden_rules']), 2)

    def test_context_updater_agent(self):
        """Test context updater agent"""
        agent = ContextUpdaterAgent(self.config, self.state)

        # Simulate vital information
        vital_info = {
            'golden_rules': ['Rule 1: Test', 'Rule 2: Document'],
            'configuration': {'version': '1.0.0'},
            'project_overview': 'Test project'
        }

        # Update context
        agent.update_context(vital_info)

        # Check if context file was created
        context_file = os.path.join(self.test_dir, 'ALWAYS_AVAILABLE_CONTEXT.md')
        self.assertTrue(os.path.exists(context_file))

        with open(context_file, 'r') as f:
            content = f.read()

        self.assertIn('Rule 1: Test', content)
        self.assertIn('Rule 2: Document', content)
        self.assertIn('version: 1.0.0', content)


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