from pathlib import Path

from fastapi import APIRouter
from fastapi import Depends
from fastapi import HTTPException
from fastapi import Request
from fastapi.responses import HTMLResponse

from ghostforge.templates import templates
from ghostforge.users import get_current_user
from markdown import markdown

gf = APIRouter()

markdown_dir = Path("ghostforge/markdown/")


def render_markdown(md_file):
    with open(markdown_dir / md_file, "r") as f:
        return markdown(f.read())


@gf.get("/guidebook", response_class=HTMLResponse)
async def guidebook_page(request: Request, current_user=Depends(get_current_user(optional=True))):
    if not current_user:
        return HTTPException(status_code=401, detail="Not authenticated")
    data = {
        "title": "Guidebook",
        "html": render_markdown("guidebook.md"),
        "user": current_user,
        "crumbs": [("research", False), ("guidebook", False)],
    }
    return templates.TemplateResponse("pages.html", data | {"request": request})
