import os
import json
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates


class CategoryController:
    def __init__(self,data_file="generated_data.json"):
        """Initialize the controller."""
        self.router = APIRouter()
        self.templates = Jinja2Templates(directory="templates")
        self.data = self._load_data( data_file )
        self._add_routes()

    def _add_routes(self):
        """Add routes to the router."""
        self.router.add_api_route("/", self.get_index, methods=["GET"], response_class=HTMLResponse)
        self.router.add_api_route(
            "/category/{category_name}",
            self.get_category,
            methods=["GET"],
            response_class=HTMLResponse,
        )
    def _load_data(self, data_file):
        """Load JSON data from a file."""
        with open(data_file, "r", encoding="utf-8") as file:
            return json.load(file)

    async def get_index(self, request: Request):
        """Index route."""
        return self.templates.TemplateResponse(
            "index.html",
            {"request": request, "data": self.data, "page_title": "Forside", "author": "Henrik"},
        )

    async def get_category(self, request: Request, category_name: str):
        """Category route."""
        category = next((cat for cat in self.data["categories"] if cat["path"] == category_name), None)
        if category:
            category_file = f"data/{category_name}/index.html"
            if os.path.exists(category_file):
                with open(category_file) as file:
                    category_content = file.read()
                return self.templates.TemplateResponse(
                    "category.html",
                    {
                        "request": request,
                        "data": self.data,
                        "page_title": category["name"],
                        "author": category["author"],
                        "content": category_content,
                    },
                )
        return HTMLResponse("Kategori ikke fundet", status_code=404)
