"""
API route: Content Templates + RSS Feeds
Ported từ BrightBean apps/composer — cung cấp 30+ content templates và RSS feed catalog
"""
from fastapi import APIRouter, Query

from common.content_templates import (get_categories, get_feed_categories, get_feeds, get_template, get_templates,
                                      search_templates)

router = APIRouter(prefix="/api/templates", tags=["templates"])


@router.get("")
def list_templates(category: str = "all", limit: int = 50):
    """Liệt kê content templates theo category."""
    return {
        "templates": get_templates(category=category, limit=limit),
        "categories": get_categories(),
    }


@router.get("/categories")
def list_categories():
    return {"categories": get_categories()}


@router.get("/search")
def search(q: str = Query(..., min_length=2)):
    return {"templates": search_templates(q)}


@router.get("/{template_id}")
def get_one(template_id: int):
    t = get_template(template_id)
    if not t:
        from fastapi import HTTPException
        raise HTTPException(404, "Template not found")
    return t


@router.get("/feeds/categories")
def feed_categories():
    return {"categories": get_feed_categories()}


@router.get("/feeds/{category}")
def feeds_for_category(category: str):
    return {"feeds": get_feeds(category)}
