"""
ContextUpdater Agent - Updates context files with vital information
"""

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

from . import EventDrivenAgent
from ..core.config import Config
from ..core.state import StateManager
from ..core.utils import format_timestamp, truncate_text


class ContextUpdaterAgent(EventDrivenAgent):
    """Agent responsible for updating context files with extracted vital information"""

    def __init__(self, config: Config, state_manager: StateManager):
        super().__init__('context_updater', config, state_manager)
        self.context_dir = Path(config.workspace_path) / '.vmw'
        self.context_file = self.context_dir / config.get('output.context_file', 'ALWAYS_AVAILABLE_CONTEXT.md')
        self.vital_file = self.context_dir / config.get('output.vital_updates_file', 'VITAL_UPDATES.md')

    def process_event(self, event: Dict[str, Any]) -> Dict[str, Any]:
        """Process vital info extraction events and update context files"""
        if event['type'] != 'vital_info_extracted':
            return {'processed': False}

        vital_info = event.get('vital_info', {})

        # Update main context file
        self.update_main_context(vital_info)

        # Update vital updates file
        self.update_vital_updates(vital_info)

        return {
            'context_updated': True,
            'vital_updates_file': str(self.vital_file),
            'files_with_info': len(vital_info)
        }

    def update_main_context(self, vital_info: Dict[str, Any]):
        """Update the main ALWAYS_AVAILABLE_CONTEXT.md file"""
        self.context_dir.mkdir(exist_ok=True)

        # Read existing content or create new
        if self.context_file.exists():
            with open(self.context_file, 'r') as f:
                content = f.read()
        else:
            content = self.create_base_context()

        # Add vital updates section
        vital_section = self.generate_vital_section(vital_info)

        # Insert or replace vital section
        if "## 🔄 **Vital Context Updates**" in content:
            # Replace existing section
            import re
            pattern = r'(## 🔄 \*\*Vital Context Updates\*\*.*?)(\n##|\Z)'
            content = re.sub(pattern, f'\\1{vital_section}\\2', content, flags=re.DOTALL)
        else:
            # Add new section before final notes
            if "*🎉 This context is automatically maintained*" in content:
                content = content.replace(
                    "*🎉 This context is automatically maintained*",
                    vital_section + "\n*🎉 This context is automatically maintained*"
                )
            else:
                content += "\n" + vital_section

        # Write back
        with open(self.context_file, 'w') as f:
            f.write(content)

    def create_base_context(self) -> str:
        """Create base context file content"""
        return f"""# 🧠 AI Assistant Context
*Auto-generated: {format_timestamp()}*

## 📋 **Quick Status Overview**

🎯 **Project:** {Path(self.config.workspace_path).name}
🏗️ **Context System:** Active
📊 **Last Update:** {format_timestamp()}

---

## 🔄 **Vital Context Updates**

*No updates yet - monitoring active*

---

*🎉 This context is automatically maintained and always current!*
"""

    def generate_vital_section(self, vital_info: Dict[str, Any]) -> str:
        """Generate the vital updates section"""

        section = f"""

### Latest Updates ({format_timestamp()})

"""

        if not vital_info:
            section += "*No recent vital updates*\n"
            return section

        for file_path, info in vital_info.items():
            section += f"**📄 {file_path}:**\n"

            if info['type'] == 'markdown':
                if 'golden_rules' in info:
                    section += f"- Golden Rules updated\n"
                if 'project_overview' in info:
                    section += f"- Project overview updated\n"
                if info.get('sections'):
                    section += f"- Sections: {', '.join(info['sections'][:3])}\n"

            elif info['type'] == 'yaml':
                if 'services' in info:
                    section += f"- Services: {', '.join(info['services'][:5])}\n"
                    section += f"- Total services: {info.get('service_count', 0)}\n"

            elif info['type'] == 'python':
                if info.get('classes'):
                    section += f"- Classes: {', '.join(info['classes'])}\n"
                if info.get('functions'):
                    section += f"- Functions: {len(info['functions'])} defined\n"

            elif info['type'] == 'env':
                if info.get('variables'):
                    section += f"- Variables: {', '.join(info['variables'][:3])}\n"

            section += "\n"

        return section

    def update_vital_updates(self, vital_info: Dict[str, Any]):
        """Update the detailed vital updates file"""
        self.context_dir.mkdir(exist_ok=True)

        content = f"""# 🔄 Vital Context Updates
*Generated: {format_timestamp()}*

This file contains detailed information about recent changes detected by the Context Custodians system.

"""

        if not vital_info:
            content += "## No Recent Updates\n\nMonitoring active...\n"
        else:
            content += "## Recent File Changes\n\n"
            for file_path, info in vital_info.items():
                content += f"### {file_path}\n\n"
                content += f"**Type:** {info['type']}\n\n"

                if info['type'] == 'markdown':
                    if 'golden_rules' in info:
                        content += f"**Golden Rules:**\n{truncate_text(info['golden_rules'], 1000)}\n\n"
                    if 'project_overview' in info:
                        content += f"**Project Overview:**\n{truncate_text(info['project_overview'], 500)}\n\n"

                elif info['type'] == 'yaml':
                    if 'services' in info:
                        content += f"**Services:** {', '.join(info['services'])}\n\n"

                elif info['type'] == 'python':
                    if info.get('classes'):
                        content += f"**Classes:** {', '.join(info['classes'])}\n\n"
                    if info.get('functions'):
                        content += f"**Functions:** {', '.join(info['functions'][:20])}\n\n"

                content += "---\n\n"

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