import logging
from datetime import datetime, timezone
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from devplacepy.database import get_table, load_comments
from devplacepy.attachments import get_attachments_batch, link_attachments
from devplacepy.templating import templates
from devplacepy.utils import generate_uid, require_user, time_ago, get_current_user, create_mention_notifications
from devplacepy.seo import base_seo_context

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("", response_class=HTMLResponse)
async def bugs_page(request: Request):
    user = get_current_user(request)
    bugs_table = get_table("bug_reports")
    all_bugs = list(bugs_table.find(order_by=["-created_at"]))

    from devplacepy.database import get_users_by_uids
    uids = [b["user_uid"] for b in all_bugs]
    users_map = get_users_by_uids(uids)

    bug_list = []
    bug_uids = [b["uid"] for b in all_bugs]
    attachments_map = get_attachments_batch("bug", bug_uids) if bug_uids else {}
    for b in all_bugs:
        bug_list.append({
            "bug": b,
            "author": users_map.get(b["user_uid"]),
            "time_ago": time_ago(b["created_at"]),
            "comments": load_comments("bug", b["uid"]),
            "attachments": attachments_map.get(b["uid"], []),
        })

    seo_ctx = base_seo_context(
        request,
        title="Bug Reports",
        description="Report bugs and issues on DevPlace.",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Bug Reports", "url": "/bugs"},
        ],
    )
    return templates.TemplateResponse(request, "bugs.html", {
        **seo_ctx,
        "request": request,
        "user": user,
        "bugs": bug_list,
    })


@router.post("/create")
async def create_bug(request: Request):
    user = require_user(request)
    form = await request.form()
    title = form.get("title", "").strip()
    description = form.get("description", "").strip()

    if not title or not description:
        return RedirectResponse(url="/bugs", status_code=302)

    bugs_table = get_table("bug_reports")
    bug_uid = generate_uid()
    bugs_table.insert({
        "uid": bug_uid,
        "user_uid": user["uid"],
        "title": title,
        "description": description,
        "status": "open",
        "created_at": datetime.now(timezone.utc).isoformat(),
    })

    attachment_uids = form.getlist("attachment_uids") if hasattr(form, "getlist") else []
    if attachment_uids:
        link_attachments(attachment_uids, "bug", bug_uid)

    create_mention_notifications(description, user["uid"], f"/bugs?highlight={bug_uid}")
    logger.info(f"Bug report created by {user['username']}: {title}")
    return RedirectResponse(url="/bugs", status_code=302)
