"""
FileWatcher Agent - Monitors file changes
"""

import logging
from pathlib import Path
from typing import Dict, Any, List

from . import EventDrivenAgent
from ..core.config import Config
from ..core.state import StateManager
from ..core.utils import find_files_by_patterns, should_ignore_file


class FileWatcherAgent(EventDrivenAgent):
    """Agent responsible for monitoring file changes"""

    def __init__(self, config: Config, state_manager: StateManager):
        super().__init__('file_watcher', config, state_manager)
        self.workspace_path = Path(config.workspace_path)
        self.watched_files = config.watched_files
        self.ignored_patterns = config.get('monitoring.ignored_patterns', [])

    def execute(self) -> Dict[str, Any]:
        """Scan for file changes"""
        self.logger.info("Scanning for file changes...")

        # Find all files matching patterns
        found_files = find_files_by_patterns(self.workspace_path, self.watched_files)

        # Filter out ignored files
        filtered_files = {}
        for file_path_str, file_path in found_files.items():
            if not should_ignore_file(file_path_str, self.ignored_patterns):
                filtered_files[file_path_str] = file_path

        # Check for changes
        changed_files = self.state_manager.get_changed_files(filtered_files)

        if changed_files:
            self.logger.info(f"Detected {len(changed_files)} changed files")
            # Update hashes for all files (changed and unchanged)
            self.state_manager.update_file_hashes(filtered_files)

            # Create event for changed files
            event = {
                'type': 'files_changed',
                'changed_files': list(changed_files.keys()),
                'timestamp': self.state_manager.get_last_scan()
            }
            self.add_event(event)

            return {
                'files_scanned': len(filtered_files),
                'files_changed': len(changed_files),
                'changed_files_list': list(changed_files.keys())
            }
        else:
            # Update hashes even if no changes (for new files)
            self.state_manager.update_file_hashes(filtered_files)
            self.logger.debug(f"No changes detected in {len(filtered_files)} files")

            return {
                'files_scanned': len(filtered_files),
                'files_changed': 0
            }

    def process_event(self, event: Dict[str, Any]) -> Dict[str, Any]:
        """Process file change events"""
        if event['type'] == 'files_changed':
            # This agent doesn't process events, it creates them
            # Events are consumed by other agents
            return {'processed': True}

        return {'processed': False}