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

from app.services.metadata_processor import MetadataProcessor


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,
        )
        self.router.add_api_route(
            "/categories", self.list_categories, methods = ["GET"], response_class = JSONResponse
        )

    def _load_data(self, data_file):
        """Load JSON data from a file. If the file is missing, generate it."""
        if not os.path.exists(data_file):
            print(f"{data_file} not found. Generating JSON...")
            self.generate_json()  # Call the JSON generation method
        with open(data_file, "r", encoding="utf-8") as file:
            return json.load(file)

    async def get_index(self, request: Request):
        """
            Handle requests for the index (home) page.

            This function is executed every time the root route (index page) is accessed.
            It renders the 'index.html' template and populates it with dynamic data, such as:
                - 'page_title': A static title for the home page ("Forside").
                - 'author': The author's name ("Henrik").
                - 'data': General data accessible to the template.

            Args:
                request (Request): The HTTP request object.

            Returns:
                TemplateResponse: A rendered HTML page for the index (home) route.
        """

        unix_time_now = int( time.time() )
        with open(f"data/_frontpage/index.html", "r") as fp:
            content = fp.read()

        return self.templates.TemplateResponse(
            "category.html",
            {
                "request": request,
                "data": self.data,
                "page_title": "Frontpage",
                "author": "Henrik Jess",
                "content": content,
                "timestamp": unix_time_now
            })


    async def get_category(self, request: Request, category_name: str):
        """
           Handle requests for specific category pages.

           This function is executed every time a category route is accessed.
           It dynamically retrieves and serves content for the requested category.
           - Searches for the requested category in 'self.data["categories"]' based on the provided category name.
           - Reads the 'index.html' file located under 'data/{category_name}/' if it exists.
           - Returns the rendered 'category.html' template with the following dynamic data:
               - 'page_title': The name of the category.
               - 'author': The author of the category.
               - 'content': The content of the 'index.html' file.
               - 'timestamp': The current Unix time when the request is processed.
             - Returns a 404 HTML response if the category is not found or the file does not exist.

           Args:
               request (Request): The HTTP request object.
               category_name (str): The name of the category being accessed.

           Returns:
               TemplateResponse: A rendered HTML page with dynamic category content.
               HTMLResponse: A 404 response if the category does not exist.
        """
        category = next((cat for cat in self.data["categories"] if cat["path"] == category_name), None)
        unix_time_now = int( time.time() )
        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,
                        "timestamp": unix_time_now
                    },
                )
        return HTMLResponse("Kategori ikke fundet", status_code=404)

    async def list_categories(self, request: Request):
        """Return a list of all categories with their name and path."""
        categories = [
            { "name": category["name"], "path": category["path"] }
            for category in self.data.get( "categories", [] )
        ]
        return JSONResponse( content = categories )