from jinja2 import Environment, FileSystemLoader
from xhtml2pdf import pisa
import os
import logging
from enum import Enum
from datetime import datetime

logger = logging.getLogger(__name__)

class SmartStr(str):
    def strftime(self, format_str):
        val = self.strip()
        if not val:
            return "Not Available"
        
        # Try parsing various datetime formats
        for fmt in (
            '%Y-%m-%dT%H:%M:%S.%f%z',
            '%Y-%m-%dT%H:%M:%S%z',
            '%Y-%m-%dT%H:%M:%S.%f',
            '%Y-%m-%dT%H:%M:%S',
            '%Y-%m-%d %H:%M:%S.%f',
            '%Y-%m-%d %H:%M:%S',
            '%Y-%m-%d',
        ):
            try:
                s = val
                if s.endswith('Z'):
                    s = s[:-1] + '+00:00'
                if hasattr(datetime, 'fromisoformat'):
                    dt = datetime.fromisoformat(s)
                else:
                    dt = datetime.strptime(s, fmt)
                return dt.strftime(format_str)
            except Exception:
                continue
        return val

def serialize_value(v):
    if hasattr(v, "model_dump"):
        try:
            return serialize_value(v.model_dump(mode="json"))
        except Exception:
            return serialize_value(v.model_dump())
    elif hasattr(v, "dict"):
        return serialize_value(v.dict())
    elif isinstance(v, dict):
        return {k: serialize_value(val) for k, val in v.items()}
    elif isinstance(v, list):
        return [serialize_value(val) for val in v]
    elif isinstance(v, tuple):
        return tuple(serialize_value(val) for val in v)
    elif isinstance(v, Enum):
        return v.value
    elif isinstance(v, str):
        return SmartStr(v)
    else:
        return v

def link_callback(uri, rel):
    """
    Convert HTML paths to physical file paths for xhtml2pdf to avoid deadlocking/network overhead.
    """
    if uri.startswith("http://") or uri.startswith("https://"):
        parts = uri.split("/", 3)
        if len(parts) >= 4:
            uri = "/" + parts[3]
            
    # Resolve relative to project root
    project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    
    if uri.startswith("/static/"):
        path = os.path.join(project_root, uri.lstrip("/"))
        if os.path.exists(path):
            return path
            
    if uri.startswith("/uploads/"):
        path = os.path.join(project_root, uri.lstrip("/"))
        if os.path.exists(path):
            return path
            
    return uri

def generate_pdf(template_name: str, context: dict, output_path: str) -> bool:
    try:
        # Ensure output directory exists
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        
        env = Environment(loader=FileSystemLoader("app/templates"), autoescape=True)
        template = env.get_template(template_name)
        
        serialized_context = serialize_value(context)
        html = template.render(**serialized_context)
        
        # Log the HTML for debugging
        logger.info(f"Generated HTML length: {len(html)}")

        with open(output_path, "w+b") as result_file:
            pisa_status = pisa.CreatePDF(
                html, 
                dest=result_file, 
                encoding='utf-8',
                link_callback=link_callback
            )

        if pisa_status.err:
            logger.error(f"PDF generation errors: {pisa_status.err}")
            return False
            
        return True
    except Exception as e:
        import traceback
        logger.error(f"PDF generation failed: {e}\n{traceback.format_exc()}")
        return False
