import uvicorn
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import json
import os

from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from fastapi.middleware.trustedhost import TrustedHostMiddleware


app = FastAPI()

# Mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")


# Templates directory
templates = Jinja2Templates(directory="templates")

# Load JSON data
with open("mock_data.json") as file:
	data = json.load(file)

# Index route
@app.get("/", response_class=HTMLResponse)
async def get_index(request: Request):
	return templates.TemplateResponse(
		"index.html",
		{"request": request, "data": data, "page_title": "Forside", "author": "Henrik"}
	)

# Category route
@app.get("/category/{category_name}", response_class=HTMLResponse)
async def get_category(request: Request, category_name: str):
	# Find den korrekte kategori
	category = next((cat for cat in 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 templates.TemplateResponse(
				"category.html",
				{
					"request": request,
					"data": data,
					"page_title": category["name"],
					"author": category["author"],
					"content": category_content
				},
			)
	return HTMLResponse("Kategori ikke fundet", status_code=404)

# Main entry point
def main():
    """Run the FastAPI app directly"""
    uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True, proxy_headers=True)


# Run main when executed directly
if __name__ == "__main__":
    main()