"""
Utility functions for Context Custodians
"""

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


def setup_logging(level: str = 'INFO', log_file: Path = None):
    """Setup logging configuration"""
    numeric_level = getattr(logging, level.upper(), logging.INFO)

    handlers = [logging.StreamHandler()]
    if log_file:
        handlers.append(logging.FileHandler(log_file))

    logging.basicConfig(
        level=numeric_level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=handlers
    )


def find_files_by_patterns(root_path: Path, patterns: List[str]) -> Dict[str, Path]:
    """Find files matching given patterns"""
    found_files = {}

    for pattern in patterns:
        # Convert glob pattern to regex
        regex_pattern = pattern.replace('.', '\\.').replace('*', '.*').replace('?', '.')
        regex = re.compile(f'^{regex_pattern}$', re.IGNORECASE)

        for file_path in root_path.rglob('*'):
            if file_path.is_file():
                relative_path = str(file_path.relative_to(root_path))
                if regex.match(relative_path):
                    found_files[relative_path] = file_path

    return found_files


def should_ignore_file(file_path: str, ignore_patterns: List[str]) -> bool:
    """Check if file should be ignored based on patterns"""
    for pattern in ignore_patterns:
        regex_pattern = pattern.replace('.', '\\.').replace('*', '.*').replace('?', '.')
        if re.search(regex_pattern, file_path, re.IGNORECASE):
            return True
    return False


def extract_text_from_file(file_path: Path, max_lines: int = 100) -> str:
    """Extract text content from a file, limited to max_lines"""
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            lines = []
            for i, line in enumerate(f):
                if i >= max_lines:
                    break
                lines.append(line.rstrip())
            return '\n'.join(lines)
    except (OSError, IOError, UnicodeDecodeError):
        return ""


def safe_get_env_var(var_name: str, default: str = "") -> str:
    """Safely get environment variable"""
    return os.getenv(var_name, default)


def ensure_directory(path: Path):
    """Ensure directory exists"""
    path.mkdir(parents=True, exist_ok=True)


def format_timestamp(dt=None):
    """Format timestamp for display"""
    from datetime import datetime
    if dt is None:
        dt = datetime.now()
    return dt.strftime('%B %d, %Y at %H:%M UTC')


def truncate_text(text: str, max_length: int = 500, suffix: str = "...") -> str:
    """Truncate text to max_length"""
    if len(text) <= max_length:
        return text
    return text[:max_length - len(suffix)] + suffix


def merge_dicts(dict1: Dict, dict2: Dict) -> Dict:
    """Recursively merge two dictionaries"""
    result = dict1.copy()
    for key, value in dict2.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = merge_dicts(result[key], value)
        else:
            result[key] = value
    return result