"""
Utility functions shared across CLI commands
"""

import yaml
from pathlib import Path
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn
from jinja2 import Template

console = Console()

def get_template_dir():
    """Get the templates directory"""
    return Path(__file__).parent.parent.parent / 'scaffolding'

def update_runtime_config(section, data):
    """Update runtime configuration"""
    runtime_file = Path('.abi/runtime.yaml')
    
    if runtime_file.exists():
        with open(runtime_file, 'r') as f:
            config = yaml.safe_load(f) or {}
    else:
        config = {}
    
    if section not in config:
        config[section] = {}
    
    config[section].update(data)
    
    runtime_file.parent.mkdir(exist_ok=True)
    with open(runtime_file, 'w') as f:
        yaml.dump(config, f, default_flow_style=False, indent=2)

def render_template_content(template_name, context):
    """Render template content based on template name"""
    
    # Try to load from Jinja2 template files first
    template_dir = get_template_dir()
    template_path = template_dir / f"{template_name}.j2"
    
    if template_path.exists():
        with open(template_path, 'r') as f:
            template_content = f.read()
        
        template = Template(template_content)
        return template.render(**context)
    
    # Also try with different path variations
    alt_paths = [
        template_dir / f"{template_name}.py.j2",  # For Python files
        template_dir / f"{template_name.replace('/', '_')}.j2",  # Flattened names
    ]
    
    for alt_path in alt_paths:
        if alt_path.exists():
            with open(alt_path, 'r') as f:
                template_content = f.read()
            
            template = Template(template_content)
            return template.render(**context)
    
    # Fallback to hardcoded templates
    if template_name == 'agent/requirements.txt':
        return '''# Agent dependencies
fastapi>=0.100.0
uvicorn[standard]>=0.20.0
pydantic>=2.0.0
starlette>=0.27.0

# A2A Protocol
a2a-sdk
mcp
fastmcp
mcp-toolbox

# AI and LLM
langchain>=0.1.0
langchain-core>=0.2.20
langchain-ollama>=0.1.0
langchain-community>=0.1.0
langgraph>=0.1.0

# HTTP and Networking
httpx>=0.25.0
requests>=2.31.0
aiohttp>=3.8.0

# Data and Storage
redis>=4.5.0
tinydb>=4.7.0
networkx>=3.0.0

# Utilities
jinja2>=3.1.0
pyyaml>=6.0.0
psutil>=5.9.0''' + ('''

# Web Interface
sse-starlette>=1.6.0''' if context.get('with_web_interface') else '')
    
    elif template_name == 'agent/common/agent_executor.py':
        return '''"""
Base ABI Agent Class - Use abi_core.common.agent_executor instead
"""

# This is a fallback - use the real implementation from abi_core
from abi_core.agent.agent import AbiAgent

__all__ = ['AbiAgent']
'''
    
    elif template_name == 'agent/common/utils.py':
        return '''"""
Utility functions - Use abi_core.common.utils instead
"""

# This is a fallback - use the real implementation from abi_core
from abi_core.common.utils import abi_logging, truncate

__all__ = ['abi_logging', 'truncate']
'''
    
    elif template_name == 'agent/common/prompts.py':
        agent_name = context.get('agent_name', 'Agent')
        return f'''"""
Prompts for {agent_name}
"""

AGENT_SYSTEM_PROMPT = """
You are {agent_name}, a specialized AI agent.
Process queries efficiently and provide clear responses.
"""
'''
    
    elif template_name == 'agent/common/a2a_server.py':
        return '''"""
A2A Server - Use abi_core.common.a2a_server instead
"""

# This is a fallback - use the real implementation from abi_core
from abi_core.common.a2a_server import start_server

__all__ = ['start_server']
'''
    
    elif template_name == 'project_config':
        return f'''"""
Configuration for {context.get('project_name', 'ABI Project')}
Generated by ABI-Core scaffolding
"""

import os
from typing import Dict, Any

class {context.get('project_name', 'ABI').replace(' ', '').replace('-', '')}Config:
    """Configuration class for {context.get('project_name', 'ABI Project')}"""
    
    def __init__(self):
        self.project_name = "{context.get('project_name', 'ABI Project')}"
        self.description = "{context.get('description', 'ABI-powered project')}"
        self.domain = "{context.get('domain', 'general')}"
        
        # ABI Core settings
        self.abi_role = os.getenv('ABI_ROLE', '{context.get('project_name', 'ABI Project')}')
        self.abi_node = os.getenv('ABI_NODE', 'ABI Node')
        
        # Agent settings
        self.agent_host = os.getenv('AGENT_HOST', '0.0.0.0')
        self.agent_port = int(os.getenv('AGENT_PORT', '8000'))
        
        # Model settings
        self.model_name = os.getenv('MODEL_NAME', 'llama3.2:3b')
        self.ollama_host = os.getenv('OLLAMA_HOST', 'http://localhost:11434')

config = {context.get('project_name', 'ABI').replace(' ', '').replace('-', '')}Config()
'''
    
    elif template_name == 'runtime_config':
        return f'''# {context.get('project_name', 'ABI Project')} Runtime Configuration
# Generated by ABI-Core scaffolding

project:
  name: "{context.get('project_name', 'ABI Project')}"
  description: "{context.get('description', 'ABI-powered project')}"
  domain: "{context.get('domain', 'general')}"
  version: "1.0.0"

agents: {{}}

services:
{f"""  semantic_layer:
    name: "Semantic Layer"
    type: "semantic-layer"
    port: 10100
    enabled: true""" if context.get('with_semantic_layer') else ""}
{f"""  guardian:
    name: "Guardian Security"
    type: "guardian"
    port: 11438
    enabled: true""" if context.get('with_guardian') else ""}

policies: {{}}

runtime:
  mode: "development"
  log_level: "INFO"
  ports:
    start: 8000
    end: 8100
'''
    
    elif template_name == 'requirements':
        return f'''# {context.get('project_name', 'ABI Project')} Requirements
# Generated by ABI-Core scaffolding

# LangChain and AI
langchain-ollama
langchain-core
langgraph

# Web Framework
fastapi>=0.100.0
uvicorn>=0.20.0

# MCP Protocol
fastmcp>=3.2.0

# Data and Validation
pydantic>=2.0.0

# Utilities
rich>=13.0.0
click>=8.0.0
requests>=2.31.0
python-dotenv>=1.0.0
'''
    
    elif template_name == 'compose_config':
        return f'''# {context.get('project_name', 'ABI Project')} Docker Compose
version: '3.8'

services:
  {context.get('project_dir', 'abi_project').replace('-', '_')}-base:
    build: .
    ports:
      - "8000:8000"
    environment:
      - ABI_ROLE={context.get('project_name', 'ABI Project')}
      - ABI_NODE=ABI Node
    networks:
      - abi-network

{f"""  semantic-layer:
    build: ./services/semantic_layer
    ports:
      - "10100:10100"
    networks:
      - abi-network""" if context.get('with_semantic_layer') else ""}

{f"""  guardian:
    build: ./services/guardian
    ports:
      - "11438:11438"
    networks:
      - abi-network""" if context.get('with_guardian') else ""}

networks:
  abi-network:
    driver: bridge
'''
    
    elif template_name == 'dockerfile':
        return f'''# {context.get('project_name', 'ABI Project')} Dockerfile
FROM smarbuy/abi-image:latest

WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy project
COPY . .

# Expose port
EXPOSE 8000

# Run
CMD ["python", "main.py"]
'''
    
    elif template_name == 'readme':
        return f'''# {context.get('project_name', 'ABI Project')}

{context.get('description', 'ABI-powered project')}

## Quick Start

1. Install dependencies:
   ```bash
   pip install -r requirements.txt
   ```

2. Run the project:
   ```bash
   abi-core run
   ```

## Generated by ABI-Core

This project was generated using ABI-Core CLI.
'''
    
    elif template_name == 'main_app':
        return f'''#!/usr/bin/env python3
"""
{context.get('project_name', 'ABI Project')} Main Application
"""

import uvicorn
from fastapi import FastAPI
from config.config import config

app = FastAPI(
    title=config.project_name,
    description=config.description,
    version="1.0.0"
)

@app.get("/")
async def root():
    return {{
        "message": f"Welcome to {{config.project_name}}",
        "domain": config.domain,
        "status": "running"
    }}

@app.get("/health")
async def health():
    return {{
        "status": "healthy",
        "project": config.project_name,
        "domain": config.domain
    }}

@app.get("/config")
async def get_config():
    return {{
        "project_name": config.project_name,
        "description": config.description,
        "domain": config.domain,
        "abi_role": config.abi_role
    }}

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host=config.agent_host,
        port=config.agent_port,
        reload=True
    )
'''
    
    # Add more template types as needed...
    return ""