9af949c 5e51915 9af949c 997da40 9af949c c0ed382 3258e39 9af949c 3258e39 52026a0 9af949c 85b8192 52026a0 9af949c 5e51915 929fbde 259cf17 997da40 929fbde 997da40 3258e39 dc408b2 3258e39 26f0919 52026a0 3258e39 52026a0 9af949c 52026a0 9af949c 997da40 9af949c 997da40 9af949c 57dd703 e6c6972 997da40 e6c6972 9af949c 3258e39 9af949c 997da40 9af949c 997da40 c0ed382 997da40 9af949c e6c6972 9af949c 52026a0 c0ed382 997da40 02e09d2 997da40 52026a0 9af949c e6c6972 9af949c fbd311b 997da40 9af949c 997da40 52026a0 997da40 c0ed382 997da40 9af949c e6c6972 9af949c fbd311b 997da40 9af949c 997da40 c0ed382 997da40 9af949c e6c6972 9af949c bc06b34 9af949c 997da40 bc06b34 997da40 f79d162 52026a0 997da40 9af949c 997da40 9af949c 997da40 c0ed382 997da40 3258e39 997da40 52026a0 997da40 9af949c 52026a0 e6c6972 9af949c fbd311b 997da40 9af949c 997da40 c0ed382 997da40 3258e39 997da40 9af949c e6c6972 9af949c fbd311b 997da40 f79d162 52026a0 9af949c 997da40 c0ed382 997da40 f79d162 52026a0 997da40 9af949c e6c6972 9af949c 997da40 fbd311b 997da40 259cf17 9af949c f79d162 997da40 c0ed382 997da40 71f0568 997da40 71f0568 997da40 52026a0 997da40 f79d162 997da40 3258e39 997da40 9af949c e6c6972 9af949c fbd311b 997da40 9af949c 929fbde c0ed382 997da40 929fbde 997da40 9af949c 929fbde 52026a0 9af949c e6c6972 9af949c 3258e39 dc408b2 7377412 dc408b2 9af949c 3258e39 997da40 3258e39 997da40 9af949c 3258e39 e6c6972 9af949c fbd311b 997da40 259cf17 9af949c 997da40 c0ed382 997da40 3258e39 997da40 9af949c e6c6972 9af949c fbd311b 997da40 3258e39 9af949c 997da40 c0ed382 997da40 e6c6972 3258e39 997da40 3258e39 997da40 3258e39 9af949c e6c6972 dc408b2 e6c6972 dc408b2 997da40 fbd311b 997da40 dc408b2 9af949c dc408b2 997da40 c0ed382 997da40 dc408b2 997da40 3258e39 997da40 3258e39 997da40 9af949c e6c6972 dc408b2 e6c6972 9af949c fbd311b 997da40 9af949c 997da40 c0ed382 997da40 6208a28 997da40
"""
Task-related routes: Task, comment, board creation, listing, and management.
Data is stored in the repo ODB/RefDB via pygittools.tasks (Board, Task, Comment).
"""

from __future__ import annotations

import os
import re
import time
from typing import Annotated, Any
from urllib.parse import quote

import pygit2
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse

from pygittools.tasks import (
	ARCHIVE_BOARD_NAME,
	BOARD_REF_PREFIX,
	TASK_REF_PREFIX,
	Board,
	Comment,
	Task,
	archive_task_local,
	delete_task_local,
	get_board,
	get_comment,
	get_task,
	get_task_by_oid,
)
from pygitweb.auth import (
	access_token_from_request,
	ensure_active_user_if_auth_enabled,
	has_permission,
	principal_from_session,
	require_permission,
)
from pygitweb.config import settings
from pygitweb.dependencies import ValidatedReadableQueryProject, filter_projects_by_read_access
from pygitweb.gravatar import gravatar_url
from pygitweb.permissions import Permission, PermissionPrincipal
from pygitweb.projects import git_get_projects_list
from pygitweb.templates_env import POSTAMBLE, PREAMBLE, env, jinja_escape

# Well-known empty tree OID for boards/tasks when repo has no HEAD
EMPTY_TREE_OID = pygit2.Oid(hex="4b825dc642cb6eb9a060e54bf8d69288fbee4904")

# Allowed sprint story point values (Fibonacci scale). Anything else is treated as unestimated.
SPRINT_POINTS: tuple[int, ...] = (0, 1, 2, 3, 5, 8, 13, 21)


def _parse_points(raw: Any) -> int | None:
	"""Parse a story points value, keeping only values on the Fibonacci scale."""
	if raw is None or raw == "":
		return None
	try:
		value = int(raw)
	except (TypeError, ValueError):
		return None
	return value if value in SPRINT_POINTS else None


def _board_ref(name: str) -> str:
	return f"{BOARD_REF_PREFIX}{name}"


def _task_ref(task_id: str) -> str:
	return f"{TASK_REF_PREFIX}{task_id}"


def _repo_head_or_empty(repo: pygit2.Repository) -> pygit2.Oid | str:
	try:
		return repo.head.target
	except KeyError:
		return EMPTY_TREE_OID


def _sync_board_task_oid(
	repo: pygit2.Repository,
	board: str,
	old_oid: str,
	new_oid: pygit2.Oid | str,
	*,
	move_to_end: bool = False,
) -> None:
	"""Replace a task OID on the board after the task tag object was rewritten."""
	b = get_board(repo, _board_ref(board))
	if not b or not getattr(b, "tasks", None):
		return
	new_oid_str = str(new_oid)
	tasks_list = [new_oid_str if o == old_oid else o for o in b.tasks]
	if move_to_end and new_oid_str in tasks_list:
		tasks_list = [o for o in tasks_list if o != new_oid_str] + [new_oid_str]
	b.tasks = tasks_list
	b.update_message()
	b.write(repo)


def _task_from_board_entry(
	repo: pygit2.Repository,
	oid_hex: str | pygit2.Oid,
	*,
	board: str | None = None,
) -> Task | None:
	"""
	Load a task listed on a board by OID.

	Board entries can lag behind ``refs/tags/tasks/…`` after a task rewrite (e.g. a new
	comment). When the ref points at a newer tag object, return that version and repair
	the board list when ``board`` is provided.
	"""
	oid = pygit2.Oid(hex=oid_hex) if isinstance(oid_hex, str) else oid_hex
	t = get_task_by_oid(repo, oid)
	if not t or not t.name:
		return t
	try:
		if t.name not in repo.references:
			return t
		current_oid = repo.references[t.name].resolve().target
	except KeyError:
		return t
	if str(current_oid) == str(oid):
		return t
	t_current = get_task(repo, t.name)
	if t_current and board:
		_sync_board_task_oid(repo, board, str(oid), current_oid)
	return t_current or t


def create_board_for_project(
	project: str,
	name: str = "Tasks",
	description: str = "",
) -> str:
	"""Create a board in the project repo. Returns the board ref. Raises HTTPException on error."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = _board_ref(name)
	if ref in repo.references:
		raise HTTPException(status_code=409, detail="Board already exists")
	target = _repo_head_or_empty(repo)
	board = Board(target, ref, tagger="", description=description)
	board.write(repo)
	return ref


# ---------- Board Routes ----------

board_router = APIRouter(tags=["boards"])


def list_project_boards(project: str) -> list[dict[str, Any]]:
	"""Return [{name, description, task_count}, ...] for every board in a project."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	refs = [
		(ref_name, str(repo.references[ref_name].resolve().target))
		for ref_name in repo.references
		if ref_name.startswith(BOARD_REF_PREFIX)
	]
	boards = []
	for ref_name, _ in refs:
		try:
			b = get_board(repo, ref_name)
			if b:
				boards.append({
					"name": ref_name.replace(BOARD_REF_PREFIX, ""),
					"description": getattr(b, "description", "") or "",
					"task_count": len(getattr(b, "tasks", [])),
				})
		except (ValueError, KeyError):
			continue
	return boards


@board_router.get(
	"/list",
	response_class=JSONResponse,
)
def boards_list(project: ValidatedReadableQueryProject) -> JSONResponse:
	"""List all boards for the project."""
	return JSONResponse(content=list_project_boards(project))


@board_router.post(
	"/create",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.BOARDS, project_from_query=True))],
)
def boards_create(
	project: ValidatedReadableQueryProject,
	name: str = Query(..., description="Board name"),
	description: str = Query("", description="Board description"),
) -> JSONResponse:
	"""Create a new board."""
	if not name or not pygit2.reference_is_valid_name(_board_ref(name)):
		raise HTTPException(status_code=400, detail="Invalid board name")
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = _board_ref(name)
	if ref in repo.references:
		raise HTTPException(status_code=409, detail="Board already exists")
	target = _repo_head_or_empty(repo)
	board = Board(target, ref, tagger="", description=description or "")
	oid = board.write(repo)
	return JSONResponse(content={"name": name, "ref": ref, "oid": str(oid)})


@board_router.post(
	"/delete",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.BOARDS, project_from_query=True))],
)
def boards_delete(
	project: ValidatedReadableQueryProject,
	name: str = Query(..., description="Board name"),
) -> JSONResponse:
	"""Delete a board (removes ref; tag object remains in ODB)."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = _board_ref(name)
	if ref not in repo.references:
		raise HTTPException(status_code=404, detail="Board not found")
	repo.references.delete(ref)
	return JSONResponse(content={"message": "Board deleted"})


# ---------- Task Routes ----------

task_router = APIRouter(tags=["tasks"])


def _task_display_id(ref: str) -> str:
	"""Numeric task id for UI (task_1730000000000 -> 1730000000000)."""
	slug = ref.removeprefix(TASK_REF_PREFIX)
	if slug.startswith("task_"):
		return slug.removeprefix("task_")
	return slug


def _task_to_json(t: Task) -> dict[str, Any]:
	return {
		"ref": t.name,
		"id": _task_display_id(t.name),
		"title": t.title,
		"description": getattr(t, "description", "") or "",
		"status": t.status.value if t.status else None,
		"priority": t.priority.value if t.priority else None,
		"assignee": t.assignee,
		"due_date": t.due_date.isoformat() if t.due_date else None,
		"tags": getattr(t, "tags", "") or "",
		"points": getattr(t, "points", None),
		"created_at": t.created_at.isoformat() if t.created_at else None,
		"updated_at": t.updated_at.isoformat() if t.updated_at else None,
		"comments_count": len(getattr(t, "comments", [])),
	}


# Status order for board columns
BOARD_STATUS_ORDER = ["TODO", "IN_PROGRESS", "IN_REVIEW", "DONE", "CANCELLED"]


def get_board_tasks_grouped(
	project: str,
	board_name: str,
) -> list[dict[str, Any]]:
	"""
	Return tasks for a board grouped by status for board view.
	Returns a list of { "status": str, "label": str, "tasks": [ _task_to_json, ... ] }
	in BOARD_STATUS_ORDER. Skips validation/auth (caller must validate project).
	"""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = _board_ref(board_name)
	b = get_board(repo, ref)
	task_oids = getattr(b, "tasks", []) or []
	by_status: dict[str, list[dict[str, Any]]] = {s: [] for s in BOARD_STATUS_ORDER}
	for oid_hex in task_oids:
		try:
			t = _task_from_board_entry(repo, oid_hex, board=board_name)
			if t:
				d = _task_to_json(t)
				status_key = (d.get("status") or "TODO") if d else "TODO"
				if status_key not in by_status:
					by_status[status_key] = []
				by_status[status_key].append(d)
		except (ValueError, KeyError, TypeError):
			continue
	return [
		{
			"status": s,
			"label": s.replace("_", " ").title(),
			"tasks": by_status.get(s, []),
			"points_total": sum(t.get("points") or 0 for t in by_status.get(s, [])),
		}
		for s in BOARD_STATUS_ORDER
	]


def get_all_project_tasks(project: str) -> list[dict[str, Any]]:
	"""
	Return every task across all boards in a project, each tagged with its board name.

	Used by the team overview page, which needs to see who has what regardless of
	which board a task currently sits on. Skips validation/auth (caller must validate project).
	"""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	out: list[dict[str, Any]] = []
	for ref_name in repo.references:
		if not ref_name.startswith(BOARD_REF_PREFIX):
			continue
		board_name = ref_name.removeprefix(BOARD_REF_PREFIX)
		b = get_board(repo, ref_name)
		for oid_hex in getattr(b, "tasks", []) or []:
			try:
				t = _task_from_board_entry(repo, oid_hex, board=board_name)
				if t:
					d = _task_to_json(t)
					d["board"] = board_name
					out.append(d)
			except (ValueError, KeyError, TypeError):
				continue
	return out


@task_router.get("", response_class=HTMLResponse)
def all_tasks_page(
	token: Annotated[str | None, Depends(access_token_from_request)],
	status: Annotated[str | None, Query()] = None,
) -> HTMLResponse:
	"""Flat list of every task across every project and board you can read."""
	status_filter = (status or "").strip().upper() or None
	projects = filter_projects_by_read_access(
		git_get_projects_list(paranoid=settings.STRICT_EXPORT, export_ok=settings.EXPORT_OK),
		token,
	)
	rows: list[list[str]] = []
	for pr in projects:
		project = pr.get("path", "")
		if not project:
			continue
		try:
			tasks = get_all_project_tasks(project)
		except Exception:
			continue
		for t in tasks:
			task_status = t.get("status") or "TODO"
			if status_filter and task_status != status_filter:
				continue
			project_url = f"/project/{quote(project, safe='/')}"
			board_url = f"{project_url}/board/?b={quote(t['board'], safe='')}"
			task_url = f"{board_url}&task={quote(t['ref'], safe='')}"
			rows.append([
				f"<a href='{task_url}'>{jinja_escape(t.get('title') or '(untitled)')}</a>",
				f"<a href='{project_url}'>{jinja_escape(project)}</a>",
				jinja_escape(t.get("board") or "") or "",
				jinja_escape(task_status.replace("_", " ").title()) or "",
				jinja_escape((t.get("priority") or "LOW").title()) or "",
				jinja_escape(t.get("assignee") or "Unassigned") or "",
				str(t.get("points") if t.get("points") is not None else ""),
			])
	table = env.get_template("table.html").render(
		cols=["Task", "Project", "Board", "Status", "Priority", "Assignee", "Points"],
		rows=rows,
	)
	status_options = "".join(
		f'<option value="{s}"{" selected" if status_filter == s else ""}>{s.replace("_", " ").title()}</option>'
		for s in BOARD_STATUS_ORDER
	)
	filter_form = (
		'<form method="get" action="/tasks" class="d-flex align-items-center gap-2 mb-3">'
		'<label class="form-label mb-0" for="tasks-status-filter">Status</label>'
		'<select id="tasks-status-filter" name="status" class="form-select form-select-sm" '
		'style="width: auto;" onchange="this.form.submit()">'
		f'<option value=""{" selected" if not status_filter else ""}>All</option>{status_options}'
		"</select></form>"
	)
	body = table if rows else '<p class="text-muted">No tasks found.</p>'
	pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Tasks", site_name=settings.SITE_NAME)
	return HTMLResponse(f"{pre}<h1>Tasks</h1>{filter_form}{body}{POSTAMBLE}")


@task_router.get(
	"/list",
	response_class=JSONResponse,
)
def task_list(
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Board name"),
) -> JSONResponse:
	"""List all tasks on a board."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = _board_ref(board)
	b = get_board(repo, ref)
	if not b:
		raise HTTPException(status_code=404, detail="Board not found")
	task_oids = getattr(b, "tasks", [])
	tasks = []
	for oid_hex in task_oids:
		try:
			t = _task_from_board_entry(repo, oid_hex, board=board)
			if t:
				tasks.append(_task_to_json(t))
		except (ValueError, KeyError, TypeError):
			continue
	return JSONResponse(content=tasks)


@task_router.post(
	"/create",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.TASKS, project_from_query=True))],
)
def task_create(
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Board name"),
	title: str = Query(..., description="Task title"),
	description: str = Query("", description="Task description"),
	status: str = Query("TODO", description="Task status"),
	priority: str = Query("LOW", description="Task priority"),
	assignee: str = Query("", description="Assignee"),
	due_date: str = Query("", description="Due date ISO"),
	tags: str = Query("", description="Task tags (KEY=VALUE list)"),
	points: str = Query("", description="Sprint story points (Fibonacci: 0,1,2,3,5,8,13,21)"),
) -> JSONResponse:
	"""Create a new task on a board."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	board_ref = _board_ref(board)
	b = get_board(repo, board_ref)
	if not b:
		raise HTTPException(status_code=404, detail="Board not found")
	task_id = f"task_{int(time.time() * 1000)}"
	ref = _task_ref(task_id)
	target = _repo_head_or_empty(repo)
	status_enum = getattr(Task.Status, status, None) or Task.Status.TODO
	priority_enum = getattr(Task.Priority, priority, None) or Task.Priority.LOW
	due = None
	if due_date:
		try:
			from datetime import datetime

			due = datetime.fromisoformat(due_date.replace("Z", "+00:00"))
		except ValueError:
			pass
	task = Task(
		target,
		ref,
		tagger="",
		title=title,
		description=description or "",
		status=status_enum,
		priority=priority_enum,
		assignee=assignee or None,
		due_date=due,
		tags=tags or "",
		points=_parse_points(points),
	)
	oid = task.write(repo)
	b.tasks = getattr(b, "tasks", []) or []
	b.tasks.append(str(oid))
	b.update_message()
	b.write(repo)
	return JSONResponse(content={"task_id": task_id, "ref": ref, "oid": str(oid)})


@task_router.post(
	"/update",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.TASKS, project_from_query=True))],
)
async def task_update(
	request: Request,
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Board name"),
	task_ref: str = Query(..., alias="task", description="Task ref (e.g. refs/tags/tasks/task_123)"),
) -> JSONResponse:
	"""Update a task (body: optional title, description, status, priority, assignee, due_date, tags)."""
	try:
		body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
	except Exception:
		body = {}
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = task_ref if task_ref.startswith("refs/") else _task_ref(task_ref)
	t = get_task(repo, ref)
	if not t:
		raise HTTPException(status_code=404, detail="Task not found")
	status_changed = bool("status" in body and hasattr(Task.Status, body["status"]))
	if "title" in body:
		t.title = body["title"]
	if "description" in body:
		t.description = body.get("description", "")
	if status_changed:
		t.status = Task.Status(body["status"])
	if "priority" in body and hasattr(Task.Priority, body["priority"]):
		t.priority = Task.Priority(body["priority"])
	if "assignee" in body:
		t.assignee = body["assignee"] or None
	if "points" in body:
		t.points = _parse_points(body["points"])
	if "due_date" in body:
		try:
			from datetime import datetime

			t.due_date = (
				datetime.fromisoformat(str(body["due_date"]).replace("Z", "+00:00")) if body["due_date"] else None
			)
		except ValueError:
			pass
	if "tags" in body:
		t.tags = str(body.get("tags") or "")
	old_oid = str(repo.references[ref].resolve().target)
	t.update_message()
	new_oid = t.write(repo)
	_sync_board_task_oid(repo, board, old_oid, new_oid, move_to_end=status_changed)
	return JSONResponse(content=_task_to_json(t))


@task_router.post(
	"/delete",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.TASKS, project_from_query=True))],
)
def task_delete(
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Board name"),
	task_ref: str = Query(..., alias="task", description="Task ref"),
) -> JSONResponse:
	"""Delete a task (remove ref, comments, and board entries)."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = task_ref if task_ref.startswith("refs/") else _task_ref(task_ref)
	if ref not in repo.references:
		raise HTTPException(status_code=404, detail="Task not found")
	delete_task_local(repo, ref)
	return JSONResponse(content={"message": "Task deleted"})


@task_router.post(
	"/archive",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.TASKS, project_from_query=True))],
)
def task_archive(
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Source board name"),
	task_ref: str = Query(..., alias="task", description="Task ref"),
	archive_board: str = Query(ARCHIVE_BOARD_NAME, description="Archive board name"),
) -> JSONResponse:
	"""Move a task from a board to the archive board (creates archive board if needed)."""
	if not archive_board or "/" in archive_board or ".." in archive_board:
		raise HTTPException(status_code=400, detail="Invalid archive board name")
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = task_ref if task_ref.startswith("refs/") else _task_ref(task_ref)
	try:
		archive_ref = archive_task_local(repo, ref, board, archive_board_name=archive_board)
	except KeyError as exc:
		raise HTTPException(status_code=404, detail=str(exc)) from exc
	return JSONResponse(
		content={
			"message": "Task archived",
			"archive_board": archive_board,
			"archive_ref": archive_ref,
		}
	)


@task_router.post(
	"/move",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.TASKS, project_from_query=True))],
)
def task_move(
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Source board name"),
	task_ref: str = Query(..., alias="task", description="Task ref"),
	target: str = Query(..., description="Target board name (e.g. a sprint board)"),
) -> JSONResponse:
	"""Move a task onto another board (e.g. pulling it into a sprint board)."""
	target_ref = _board_ref(target)
	if not target or not pygit2.reference_is_valid_name(target_ref):
		raise HTTPException(status_code=400, detail="Invalid board name")
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	ref = task_ref if task_ref.startswith("refs/") else _task_ref(task_ref)
	if ref not in repo.references:
		raise HTTPException(status_code=404, detail="Task not found")
	source_ref = _board_ref(board)
	if target_ref not in repo.references:
		raise HTTPException(status_code=404, detail="Target board not found")
	tb = get_board(repo, target_ref)
	if not tb:
		raise HTTPException(status_code=404, detail="Target board not found")
	if source_ref == target_ref:
		return JSONResponse(content={"message": "Task already on board", "board": target})
	oid_hex = str(repo.references[ref].resolve().target)
	tb.tasks = getattr(tb, "tasks", []) or []
	if oid_hex not in tb.tasks:
		tb.tasks.append(oid_hex)
		tb.update_message()
		tb.write(repo)
	sb = get_board(repo, source_ref) if source_ref in repo.references else None
	if sb and getattr(sb, "tasks", None) and oid_hex in sb.tasks:
		sb.tasks = [x for x in sb.tasks if x != oid_hex]
		sb.update_message()
		sb.write(repo)
	return JSONResponse(content={"message": "Task moved", "board": target})


# ---------- Comment Routes ----------

comment_router = APIRouter(tags=["comments"])


def _parse_tagger_display(tagger: str) -> tuple[str, str | None]:
	s = (tagger or "").strip()
	if not s:
		return ("Unknown", None)
	m = re.match(r"^(.+?)\s*<([^>]+)>", s)
	if m:
		name = m.group(1).strip() or "Unknown"
		return (name, m.group(2).strip())
	return (s, None)


def _tagger_from_principal(principal: PermissionPrincipal | None) -> str:
	if principal is None:
		return ""
	email = (principal.email or "").strip() or f"{principal.username}@local"
	name = principal.username.strip() or email
	return f"{name} <{email}>"


def _principal_matches_comment_tagger(tagger: str, principal: PermissionPrincipal) -> bool:
	identity = principal.identity
	if not identity:
		return False
	raw = (tagger or "").strip()
	if not raw:
		return False
	if raw == identity or raw.lower() == identity.lower():
		return True
	name, email = _parse_tagger_display(raw)
	valid_email = email and email.lower() == identity.lower()
	valid_name = name and (name == identity or name.lower() == identity.lower())
	return bool(valid_email or valid_name)


def _ensure_comment_modify_allowed(project: str, token: str | None, tagger: str) -> None:
	ensure_active_user_if_auth_enabled(token)
	if has_permission(Permission.COMMENTS, project, token=token):
		return
	principal = principal_from_session(token)
	if principal is not None and _principal_matches_comment_tagger(tagger, principal):
		return
	raise HTTPException(status_code=403, detail="Insufficient permissions")


def _comment_to_json(c: Comment) -> dict[str, Any]:
	author, email = _parse_tagger_display(c.tagger)
	return {
		"content": c.content,
		"tagger": c.tagger,
		"author": author,
		"gravatar_url": gravatar_url(email) if email else None,
		"created_at": c.created_at.isoformat() if c.created_at else None,
		"edited_at": c.edited_at.isoformat() if c.edited_at else None,
	}


def _comment_sort_key(entry: dict[str, Any]) -> str:
	return entry.get("edited_at") or entry.get("created_at") or ""


@comment_router.get(
	"/list",
	response_class=JSONResponse,
)
def comment_list(
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Board name"),
	task: str = Query(..., description="Task ref (e.g. refs/tags/tasks/task_123)"),
) -> JSONResponse:
	"""List all comments for a task."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	task_ref = task if task.startswith("refs/") else _task_ref(task)
	t = get_task(repo, task_ref)
	if not t:
		raise HTTPException(status_code=404, detail="Task not found")
	comment_oids = getattr(t, "comments", []) or []
	comments = []
	for oid_hex in comment_oids:
		try:
			oid = pygit2.Oid(hex=oid_hex) if isinstance(oid_hex, str) else oid_hex
			c = get_comment(repo, oid)
			if c:
				comments.append(_comment_to_json(c))
		except (ValueError, KeyError, TypeError):
			continue
	comments.sort(key=_comment_sort_key)
	return JSONResponse(content=comments)


@comment_router.post(
	"/create",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.COMMENTS, project_from_query=True))],
)
def comment_create(
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Board name"),
	task: str = Query(..., description="Task ref"),
	content: str = Query(..., description="Comment content"),
	token: Annotated[str | None, Depends(access_token_from_request)] = None,
) -> JSONResponse:
	"""Create a new comment on a task."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	task_ref = task if task.startswith("refs/") else _task_ref(task)
	t = get_task(repo, task_ref)
	if not t:
		raise HTTPException(status_code=404, detail="Task not found")
	try:
		target_oid = repo.references[task_ref].resolve().target
	except KeyError as exc:
		raise HTTPException(status_code=404, detail="Task not found") from exc
	tagger = _tagger_from_principal(principal_from_session(token))
	comment = Comment(target=target_oid, tagger=tagger, content=content or "")
	comment_oid = comment.write(repo)
	t.comments = getattr(t, "comments", []) or []
	t.comments.append(str(comment_oid))
	old_task_oid = str(target_oid)
	t.update_message()
	new_task_oid = t.write(repo)
	_sync_board_task_oid(repo, board, old_task_oid, new_task_oid)
	return JSONResponse(
		content={
			"oid": str(comment_oid),
			"message": "Comment created",
			"comments_count": len(t.comments),
		}
	)


@comment_router.post(
	"/modify",
	response_class=JSONResponse,
)
async def comment_modify(
	request: Request,
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Board name"),
	task: str = Query(..., description="Task ref (to update task.comments)"),
	comment_oid: str = Query(..., alias="comment", description="Comment OID hex"),
	token: Annotated[str | None, Depends(access_token_from_request)] = None,
) -> JSONResponse:
	"""Modify a comment (body: content). Author or pgw.comments grant required."""
	try:
		body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
	except Exception:
		body = {}
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	oid = pygit2.Oid(hex=comment_oid)
	c = get_comment(repo, oid)
	if not c:
		raise HTTPException(status_code=404, detail="Comment not found")
	_ensure_comment_modify_allowed(project, token, c.tagger)
	if "content" in body:
		c.content = body["content"]
	from datetime import datetime

	c.edited_at = datetime.now()
	c.update_message()
	new_oid = c.write(repo)
	task_ref = task if task.startswith("refs/") else _task_ref(task)
	t = get_task(repo, task_ref)
	if t and getattr(t, "comments", None):
		t.comments = [str(new_oid) if str(co) == comment_oid else co for co in t.comments]
		try:
			old_task_oid = str(repo.references[task_ref].resolve().target)
		except KeyError:
			old_task_oid = ""
		t.update_message()
		new_task_oid = t.write(repo)
		if old_task_oid:
			_sync_board_task_oid(repo, board, old_task_oid, new_task_oid)
	return JSONResponse(
		content={
			**_comment_to_json(c),
			"oid": str(new_oid),
			"message": "Comment updated",
		}
	)


@comment_router.post(
	"/delete",
	response_class=JSONResponse,
	dependencies=[Depends(require_permission(Permission.COMMENTS, project_from_query=True))],
)
def comment_delete(
	project: ValidatedReadableQueryProject,
	board: str = Query(..., description="Board name"),
	comment_oid: str = Query(..., alias="comment", description="Comment OID hex"),
) -> JSONResponse:
	"""Delete a comment (object remains in ODB; caller may remove from task.comments)."""
	repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
	oid = pygit2.Oid(hex=comment_oid)
	try:
		c = get_comment(repo, oid)
	except (ValueError, KeyError) as e:
		raise HTTPException(status_code=404, detail="Comment not found") from e
	if not c:
		raise HTTPException(status_code=404, detail="Comment not found")
	return JSONResponse(content={"message": "Comment deleted"})