"""
Template Module - Frontend Views
HTML view routes for template module
"""

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import logging

from app.core.database import execute_query

logger = logging.getLogger(__name__)

# APIRouter instance (module_loader kigger efter denne)
router = APIRouter()

# Templates til dette modul (relativ til module root)
templates = Jinja2Templates(directory="app/modules/_template/templates")


@router.get("/template", response_class=HTMLResponse)
async def template_page(request: Request):
    """
    Template module hovedside
    
    Args:
        request: FastAPI request object
        
    Returns:
        HTML response
    """
    try:
        # Hent items til visning
        items = execute_query(
            "SELECT * FROM template_items ORDER BY created_at DESC LIMIT 10"
        )
        
        return templates.TemplateResponse("index.html", {
            "request": request,
            "page_title": "Template Module",
            "items": items or []
        })
        
    except Exception as e:
        logger.error(f"❌ Error rendering template page: {e}")
        return templates.TemplateResponse("index.html", {
            "request": request,
            "page_title": "Template Module",
            "error": str(e),
            "items": []
        })
