import logging
from datetime import datetime, timezone
from fastapi import APIRouter, Request
from fastapi.responses import RedirectResponse
from devplacepy.database import get_table, resolve_by_slug
from devplacepy.attachments import link_attachments, delete_target_attachments
from devplacepy.templating import clear_unread_cache
from devplacepy.utils import generate_uid, require_user, create_mention_notifications

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


def resolve_target_redirect(target_type, target_uid):
    if target_type == "post":
        post = resolve_by_slug(get_table("posts"), target_uid)
        return f"/posts/{post['slug'] or post['uid']}" if post else "/feed"
    if target_type == "project":
        project = resolve_by_slug(get_table("projects"), target_uid)
        return f"/projects/{project['slug'] or project['uid']}" if project else "/projects"
    if target_type == "news":
        article = resolve_by_slug(get_table("news"), target_uid)
        if article:
            return f"/news/{article.get('slug', '') or article['uid']}"
        return "/news"
    if target_type == "bug":
        return f"/bugs?highlight={target_uid}"
    if target_type == "gist":
        gist = resolve_by_slug(get_table("gists"), target_uid)
        return f"/gists/{gist['slug'] or gist['uid']}" if gist else "/gists"
    return "/bugs"


@router.post("/create")
async def create_comment(request: Request):
    user = require_user(request)
    form = await request.form()
    content = form.get("content", "").strip()
    target_uid = form.get("target_uid") or form.get("post_uid", "")
    target_type = form.get("target_type", "post")
    parent_uid = form.get("parent_uid", "")

    redirect_url = resolve_target_redirect(target_type, target_uid)

    if not content or not target_uid:
        return RedirectResponse(url=redirect_url, status_code=302)
    if len(content) < 3:
        return RedirectResponse(url=redirect_url, status_code=302)
    if len(content) > 1000:
        return RedirectResponse(url=redirect_url, status_code=302)

    comment_uid = generate_uid()
    insert = {
        "uid": comment_uid,
        "target_uid": target_uid,
        "target_type": target_type,
        "user_uid": user["uid"],
        "content": content,
        "parent_uid": parent_uid or None,
        "created_at": datetime.now(timezone.utc).isoformat(),
    }
    if target_type == "post":
        insert["post_uid"] = target_uid
    get_table("comments").insert(insert)

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

    badges = get_table("badges")
    existing = badges.find_one(user_uid=user["uid"], badge_name="First Comment")
    if not existing:
        badges.insert({
            "uid": generate_uid(),
            "user_uid": user["uid"],
            "badge_name": "First Comment",
            "created_at": datetime.now(timezone.utc).isoformat(),
        })

    if target_type == "post":
        if parent_uid:
            comments_table = get_table("comments")
            parent = comments_table.find_one(uid=parent_uid)
            if parent and parent["user_uid"] != user["uid"]:
                notifications = get_table("notifications")
                notifications.insert({
                    "uid": generate_uid(),
                    "user_uid": parent["user_uid"],
                    "type": "reply",
                    "message": f"{user['username']} replied to your comment",
                    "related_uid": user["uid"],
                    "read": False,
                    "created_at": datetime.now(timezone.utc).isoformat(),
                })
                clear_unread_cache(parent["user_uid"])
        else:
            posts = get_table("posts")
            post = posts.find_one(uid=target_uid)
            if not post:
                post = posts.find_one(slug=target_uid)
            if post and post["user_uid"] != user["uid"]:
                notifications = get_table("notifications")
                notifications.insert({
                    "uid": generate_uid(),
                    "user_uid": post["user_uid"],
                    "type": "comment",
                    "message": f"{user['username']} commented on your post",
                    "related_uid": user["uid"],
                    "read": False,
                    "created_at": datetime.now(timezone.utc).isoformat(),
                })
                clear_unread_cache(post["user_uid"])

    create_mention_notifications(content, user["uid"], redirect_url)
    logger.info(f"Comment by {user['username']} on {target_type} {target_uid}")
    return RedirectResponse(url=redirect_url, status_code=302)


@router.post("/delete/{comment_uid}")
async def delete_comment(request: Request, comment_uid: str):
    user = require_user(request)
    comments = get_table("comments")
    comment = comments.find_one(uid=comment_uid)
    if not comment:
        return RedirectResponse(url="/feed", status_code=302)
    if comment["user_uid"] != user["uid"]:
        return RedirectResponse(url="/feed", status_code=302)
    target_type = comment.get("target_type", "post")
    target_uid = comment.get("target_uid") or comment.get("post_uid", "")
    delete_target_attachments("comment", comment_uid)
    get_table("votes").delete(target_uid=comment_uid, target_type="comment")
    comments.delete(id=comment["id"])
    logger.info(f"Comment {comment_uid} deleted by {user['username']}")
    redirect_url = resolve_target_redirect(target_type, target_uid)
    return RedirectResponse(url=redirect_url, status_code=302)
