import os
from pathlib import Path
import logging
from django.conf import settings

logger = logging.getLogger(__name__)

def get_active_template(divination_type, language='zh-hans', filename=None):
    """
    Get the active template for a given divination type from the database.
    Falls back to the file system only for backward compatibility.
    
    This function first checks if there's an active template in the database for the
    specified divination type. If found, it returns the template content.
    If not, it falls back to reading the template file from the file system.
    
    Args:
        divination_type (str): The divination type (bazi, number, liuyao)
        language (str): Language code for the template. Defaults to 'zh-hans'.
        filename (str, optional): Specific filename to look for (for file-based fallback only).
                                 If None, uses default naming based on divination type.
    
    Returns:
        str: The template content as a string
    
    Raises:
        FileNotFoundError: If the template cannot be found in the database or file system
    """
    # Lazy import to avoid circular dependencies
    from ai.models import PromptTemplate
    
    if not filename:
        # Default filename pattern for fallback
        filename = f"{divination_type}_analysis.txt"
    
    try:
        # Get the active template for this divination type from database
        template = PromptTemplate.objects.filter(
            divination_type=divination_type,
            language=language,
            status='active'
        ).order_by('-updated_at').first()
        
        if template:
            logger.debug(f"Using active database template: {template.name} [{language}]")
            return template.content
        
        if language != 'zh-hans':
            fallback_template = PromptTemplate.objects.filter(
                divination_type=divination_type,
                language='zh-hans',
                status='active'
            ).order_by('-updated_at').first()
            if fallback_template:
                logger.warning(
                    "No active template found for %s (%s); falling back to zh-hans template '%s'",
                    divination_type,
                    language,
                    fallback_template.name,
                )
                return fallback_template.content
            
    except Exception as e:
        logger.warning(f"Error fetching template from database: {str(e)}")
        # Continue to file-based fallback
    
    # Fallback to file-based template (for backward compatibility only)
    logger.warning(
        "No active template found in database for %s (%s), falling back to file-based template",
        divination_type,
        language
    )
    base_dir = Path(settings.BASE_DIR)

    if filename:
        filename_candidates = [filename]
    else:
        language_suffix = language.replace('-', '_') if language else 'default'
        filename_candidates = [
            f"{divination_type}_analysis_{language_suffix}.txt",
            f"{divination_type}_analysis.txt",
        ]

    for candidate in filename_candidates:
        template_path = base_dir / 'ai' / 'prompt_templates' / candidate
        if not os.path.exists(template_path):
            continue
        try:
            with open(template_path, 'r', encoding='utf-8') as file:
                logger.debug(f"Using file-based template: {candidate}")
                return file.read()
        except Exception as e:
            logger.error(f"Error loading template file {candidate}: {str(e)}")
            raise
    
    logger.error(
        "Template file not found for divination_type=%s, language=%s (checked: %s)",
        divination_type,
        language,
        ', '.join(filename_candidates)
    )
    raise FileNotFoundError(
        f"No template found for {divination_type} (language={language}). Please create one in the admin interface."
    )
