"""Shared color-coded deadline list: FastAPI + Jinja2 + HTMX + PostgreSQL."""

import csv
import hmac
import io
import json
import logging
import os
import re
import smtplib
import subprocess
from email.message import EmailMessage
from contextlib import asynccontextmanager
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from urllib.parse import urlencode

import calendar
from zoneinfo import ZoneInfo

import bcrypt
import jwt
from dotenv import load_dotenv
from fastapi import BackgroundTasks, Depends, FastAPI, File, Form, Request, UploadFile
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from starlette.concurrency import run_in_threadpool
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from psycopg.rows import dict_row
from psycopg.types.json import Jsonb
from psycopg_pool import ConnectionPool

ROOT = Path(__file__).parent
load_dotenv(ROOT / ".env")

P = "/api"
COOKIE = "deadline_session"
COOKIE_SECURE = os.environ.get("COOKIE_SECURE", "true").strip().lower() != "false"
JWT_SECRET = os.environ["JWT_SECRET"]

COLORS = {
    "green": {"label": "OK", "bg": "#c8e6c9", "fg": "#1b5e20"},
    "blue": {"label": "Not urgent", "bg": "#bbdefb", "fg": "#0d47a1"},
    "yellow": {"label": "Near term important", "bg": "#fff59d", "fg": "#5d4037"},
    "orange": {"label": "Very important", "bg": "#ffcc80", "fg": "#8a3a00"},
    "red": {"label": "Urgent non-extendable", "bg": "#ffcdd2", "fg": "#b71c1c"},
}
COLOR_ORDER = ("green", "blue", "yellow", "orange", "red")
SORT_FIELD = {
    "title": "lower(title)",
    "assignee": "lower(assignee)",
    "matter_no": "lower(matter_no)",
    "deadline": "deadline",
    "status": "array_position(ARRAY['green','blue','yellow','orange','red'], color)",
    "link": "hyperlink",
    "updated": "updated_at",
}
HEADINGS = [
    ("title", "Task"), ("assignee", "Assignee"), ("matter_no", "Matter No"),
    ("deadline", "Deadline"), ("status", "Urgency"), ("link", "Hyperlink"), ("updated", "Updated"),
]

pool = ConnectionPool(os.environ["DATABASE_URL"], kwargs={"row_factory": dict_row, "autocommit": True}, open=False)

SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    email TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    password_hash TEXT NOT NULL,
    is_admin BOOLEAN NOT NULL DEFAULT FALSE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS approved_emails (
    email TEXT PRIMARY KEY,
    added_by TEXT NOT NULL DEFAULT '',
    added_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS todos (
    id SERIAL PRIMARY KEY,
    title TEXT NOT NULL,
    assignee TEXT NOT NULL DEFAULT '',
    matter_no TEXT NOT NULL DEFAULT '',
    deadline DATE,
    color TEXT NOT NULL DEFAULT 'green',
    hyperlink TEXT NOT NULL DEFAULT '',
    notes TEXT NOT NULL DEFAULT '',
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_by TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_todos_deadline ON todos (deadline);
ALTER TABLE users ADD COLUMN IF NOT EXISTS reminders_enabled BOOLEAN NOT NULL DEFAULT TRUE;
CREATE TABLE IF NOT EXISTS todo_history (
    id SERIAL PRIMARY KEY,
    todo_id INTEGER NOT NULL REFERENCES todos(id) ON DELETE CASCADE,
    changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    changed_by TEXT NOT NULL DEFAULT '',
    field TEXT NOT NULL,
    old_value TEXT NOT NULL DEFAULT '',
    new_value TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_history_todo ON todo_history (todo_id, changed_at DESC);
CREATE TABLE IF NOT EXISTS cron_runs (
    run_id TEXT PRIMARY KEY,
    received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    sent INTEGER,
    error TEXT
);
ALTER TABLE cron_runs ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'reminders';
ALTER TABLE todo_history ADD COLUMN IF NOT EXISTS task_title TEXT NOT NULL DEFAULT '';
ALTER TABLE todo_history ALTER COLUMN todo_id DROP NOT NULL;
ALTER TABLE todo_history DROP CONSTRAINT IF EXISTS todo_history_todo_id_fkey;
ALTER TABLE todo_history ADD CONSTRAINT todo_history_todo_id_fkey
    FOREIGN KEY (todo_id) REFERENCES todos(id) ON DELETE SET NULL;
UPDATE todo_history h SET task_title = t.title FROM todos t WHERE h.todo_id = t.id AND h.task_title = '';
CREATE INDEX IF NOT EXISTS idx_history_changed_at ON todo_history (changed_at DESC);
ALTER TABLE todo_history ADD COLUMN IF NOT EXISTS orig_todo_id INTEGER;
ALTER TABLE todo_history ADD COLUMN IF NOT EXISTS snapshot JSONB;
ALTER TABLE todo_history ADD COLUMN IF NOT EXISTS restored_at TIMESTAMPTZ;
UPDATE todo_history SET orig_todo_id = todo_id WHERE orig_todo_id IS NULL AND todo_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_history_orig ON todo_history (orig_todo_id);
CREATE OR REPLACE FUNCTION todo_history_orig() RETURNS trigger AS $$
BEGIN
    NEW.orig_todo_id := COALESCE(NEW.orig_todo_id, NEW.todo_id);
    RETURN NEW;
END $$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_todo_history_orig ON todo_history;
CREATE TRIGGER trg_todo_history_orig BEFORE INSERT ON todo_history FOR EACH ROW EXECUTE FUNCTION todo_history_orig();
CREATE TABLE IF NOT EXISTS saved_filters (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    name TEXT NOT NULL,
    params JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (user_id, name)
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_saved_filters_name ON saved_filters (user_id, lower(name));
ALTER TABLE saved_filters ADD COLUMN IF NOT EXISTS shared BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE users ADD COLUMN IF NOT EXISTS default_filter_id INTEGER REFERENCES saved_filters(id) ON DELETE SET NULL;
CREATE TABLE IF NOT EXISTS task_comments (
    id SERIAL PRIMARY KEY,
    todo_id INTEGER NOT NULL,
    user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
    author_name TEXT NOT NULL DEFAULT '',
    body TEXT NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_comments_todo ON task_comments (todo_id, created_at);
CREATE TABLE IF NOT EXISTS overdue_alerts (
    todo_id INTEGER NOT NULL REFERENCES todos(id) ON DELETE CASCADE,
    deadline DATE NOT NULL,
    sent_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (todo_id, deadline)
);
"""
log = logging.getLogger("deadlines")


def hash_password(pw: str) -> str:
    return bcrypt.hashpw(pw.encode(), bcrypt.gensalt()).decode()


def check_password(pw: str, hashed: str) -> bool:
    return bcrypt.checkpw(pw.encode(), hashed.encode())


def seed_admin() -> None:
    email = os.environ["ADMIN_EMAIL"].strip().lower()
    password = os.environ["ADMIN_PASSWORD"]
    with pool.connection() as conn:
        row = conn.execute("SELECT id, password_hash FROM users WHERE email=%s", (email,)).fetchone()
        if row is None:
            conn.execute(
                "INSERT INTO users (email, name, password_hash, is_admin) VALUES (%s, %s, %s, TRUE)",
                (email, "Admin", hash_password(password)),
            )
        elif not check_password(password, row["password_hash"]):
            conn.execute("UPDATE users SET password_hash=%s, is_admin=TRUE WHERE id=%s", (hash_password(password), row["id"]))


LOCAL_PG_SCRIPT = ROOT.parent / "scripts" / "start_postgres.sh"


def ensure_local_postgres() -> None:
    # Preview only: the local database server stops when the workspace restarts.
    if "@127.0.0.1" in os.environ["DATABASE_URL"] and LOCAL_PG_SCRIPT.exists():
        subprocess.run(["bash", str(LOCAL_PG_SCRIPT)], timeout=280, check=False, capture_output=True)


def startup() -> None:
    ensure_local_postgres()
    pool.open(wait=True)
    with pool.connection() as conn:
        conn.execute(SCHEMA)
    seed_admin()


@asynccontextmanager
async def lifespan(_app: FastAPI):
    await run_in_threadpool(startup)
    yield
    pool.close()


app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
app.mount(f"{P}/static", StaticFiles(directory=ROOT / "static"), name="static")


@app.get("/", include_in_schema=False)
def site_root_redirect():
    return RedirectResponse(f"{P}/")


templates = Jinja2Templates(directory=ROOT / "templates")
templates.env.globals.update(P=P, COLORS=COLORS, COLOR_ORDER=COLOR_ORDER, HEADINGS=HEADINGS)


# ---------- validation helpers (ported from the desktop app) ----------

_ALLOWED_PREFIXES = ("http://", "https://", "mailto:", "file://")
_DOMAIN_RE = re.compile(r"^(www\.)?[\w.-]+\.[A-Za-z]{2,}([/:?#].*)?$")
_HOST_RE = re.compile(r"^(localhost|(\d{1,3}\.){3}\d{1,3})(:\d+)?(/.*)?$", re.IGNORECASE)
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")


def normalize_url(url: str) -> str | None:
    url = (url or "").strip()
    if not url:
        return ""
    if len(url) > 2048 or any(ch in url for ch in "\r\n\t"):
        return None
    lower = url.lower()
    if lower.startswith(_ALLOWED_PREFIXES):
        return url
    if "://" in url or lower.startswith(("javascript:", "data:")):
        return None
    if _HOST_RE.match(url):
        return "http://" + url
    if _DOMAIN_RE.match(url):
        return "https://" + url
    return None


def parse_deadline(text: str) -> date | str | None:
    """Return a date, '' if blank, or None if invalid."""
    text = (text or "").strip()
    if not text:
        return ""
    try:
        due = datetime.strptime(text[:10], "%Y-%m-%d").date()
    except ValueError:
        return None
    return due if 1900 <= due.year <= 2199 else None


TEAM_TZ = ZoneInfo("America/New_York")


def today_local() -> date:
    return datetime.now(TEAM_TZ).date()


def relative_deadline(due: date | None) -> str:
    if not due:
        return ""
    delta = (due - today_local()).days
    if delta == 0:
        return "today"
    if delta == 1:
        return "tomorrow"
    if delta == -1:
        return "yesterday"
    if delta > 1:
        return f"in {delta} days"
    return f"{-delta} days overdue"


def one_line(text: str) -> str:
    return " ".join((text or "").split())


def color_from(value: str) -> str | None:
    v = (value or "").strip().lower()
    if not v:
        return "green"
    for name in COLOR_ORDER:
        if v in (name, COLORS[name]["label"].lower()):
            return name
    return None


templates.env.globals.update(relative_deadline=relative_deadline, normalize_url=normalize_url)


# ---------- auth ----------

class NeedLogin(Exception):
    pass


class Forbidden(Exception):
    pass


@app.exception_handler(NeedLogin)
async def need_login_handler(request: Request, _exc: NeedLogin):
    if request.headers.get("HX-Request"):
        return Response(status_code=401, headers={"HX-Redirect": f"{P}/login"})
    return RedirectResponse(f"{P}/login", status_code=303)


@app.exception_handler(Forbidden)
async def forbidden_handler(_request: Request, _exc: Forbidden):
    return HTMLResponse("Not allowed", status_code=403)


def make_token(user_id: int) -> str:
    exp = datetime.now(timezone.utc) + timedelta(days=7)
    return jwt.encode({"sub": str(user_id), "exp": exp}, JWT_SECRET, algorithm="HS256")


def set_session(resp: Response, user_id: int) -> None:
    resp.set_cookie(COOKIE, make_token(user_id), httponly=True, secure=COOKIE_SECURE, samesite="lax",
                    max_age=7 * 24 * 3600, path="/")


def optional_user(request: Request) -> dict | None:
    token = request.cookies.get(COOKIE)
    if not token:
        return None
    try:
        uid = int(jwt.decode(token, JWT_SECRET, algorithms=["HS256"])["sub"])
    except (jwt.PyJWTError, ValueError, KeyError):
        return None
    with pool.connection() as conn:
        return conn.execute("SELECT id, email, name, is_admin, reminders_enabled FROM users WHERE id=%s", (uid,)).fetchone()


def require_user(request: Request) -> dict:
    user = optional_user(request)
    if user is None:
        raise NeedLogin()
    return user


def require_admin(user: dict = Depends(require_user)) -> dict:
    if not user["is_admin"]:
        raise Forbidden()
    return user


def render(request: Request, name: str, status_code: int = 200, headers: dict | None = None, **ctx):
    return templates.TemplateResponse(request, name, ctx, status_code=status_code, headers=headers)


def changed(extra: dict | None = None) -> Response:
    return Response(status_code=200, headers={"HX-Trigger": json.dumps({"tasksChanged": True, **(extra or {})}),
                                              "HX-Reswap": "none"})


@app.get(P + "/health")
def health():
    with pool.connection() as conn:
        conn.execute("SELECT 1")
    return {"ok": True}


@app.get(P + "/login", response_class=HTMLResponse)
def login_page(request: Request):
    if optional_user(request):
        return RedirectResponse(f"{P}/", status_code=303)
    return render(request, "login.html", error=None, email="")


@app.post(P + "/login", response_class=HTMLResponse)
def login(request: Request, email: str = Form(""), password: str = Form("")):
    email = email.strip().lower()
    with pool.connection() as conn:
        user = conn.execute("SELECT id, password_hash FROM users WHERE email=%s", (email,)).fetchone()
    if user is None or not check_password(password, user["password_hash"]):
        return render(request, "login.html", status_code=400, error="Wrong email or password.", email=email)
    resp = RedirectResponse(f"{P}/", status_code=303)
    set_session(resp, user["id"])
    return resp


@app.get(P + "/register", response_class=HTMLResponse)
def register_page(request: Request):
    return render(request, "register.html", error=None, form={})


@app.post(P + "/register", response_class=HTMLResponse)
def register(request: Request, name: str = Form(""), email: str = Form(""), password: str = Form("")):
    form = {"name": one_line(name), "email": email.strip().lower()}
    error = None
    if not form["name"]:
        error = "Please enter your name."
    elif not _EMAIL_RE.match(form["email"]):
        error = "Please enter a valid email."
    elif len(password) < 8:
        error = "Password must be at least 8 characters."
    if error:
        return render(request, "register.html", status_code=400, error=error, form=form)
    with pool.connection() as conn:
        approved = conn.execute("SELECT 1 FROM approved_emails WHERE email=%s", (form["email"],)).fetchone()
        if not approved:
            return render(request, "register.html", status_code=403, form=form,
                          error="This email has not been approved yet. Ask the admin to add it.")
        if conn.execute("SELECT 1 FROM users WHERE email=%s", (form["email"],)).fetchone():
            return render(request, "register.html", status_code=400, form=form,
                          error="An account with this email already exists. Sign in instead.")
        user = conn.execute(
            "INSERT INTO users (email, name, password_hash) VALUES (%s, %s, %s) RETURNING id",
            (form["email"], form["name"], hash_password(password)),
        ).fetchone()
    resp = RedirectResponse(f"{P}/", status_code=303)
    set_session(resp, user["id"])
    return resp


@app.post(P + "/logout")
def logout():
    resp = RedirectResponse(f"{P}/login", status_code=303)
    resp.delete_cookie(COOKIE, path="/")
    return resp


@app.post(P + "/me/name", response_class=HTMLResponse)
def update_name(request: Request, name: str = Form(""), user: dict = Depends(require_user)):
    new_name = one_line(name) or user["name"]
    with pool.connection() as conn:
        conn.execute("UPDATE users SET name=%s WHERE id=%s", (new_name, user["id"]))
    return HTMLResponse(f'<span class="saved-flash" data-testid="name-saved">Saved</span>')


@app.post(P + "/me/reminders", response_class=HTMLResponse)
def update_reminders(enabled: str = Form(""), user: dict = Depends(require_user)):
    with pool.connection() as conn:
        conn.execute("UPDATE users SET reminders_enabled=%s WHERE id=%s", (enabled == "1", user["id"]))
    return HTMLResponse('<span class="saved-flash" data-testid="reminders-saved">Saved</span>')


# ---------- pages ----------

@app.get(P, include_in_schema=False)
def root_redirect():
    return RedirectResponse(f"{P}/", status_code=307)


@app.get(P + "/", response_class=HTMLResponse)
def index(request: Request, user: dict = Depends(require_user)):
    return render(request, "index.html", user=user, people=people_names(), default_filter=default_filter(user))


# ---------- tasks ----------

MINE_SQL = "lower(btrim(assignee)) IN (lower(%s), lower(%s))"


def filter_sql(q: str, matter: str, mine_user: dict | None) -> tuple[list[str], list]:
    where, params = [], []
    if mine_user:
        where.append(MINE_SQL)
        params += [mine_user["name"], mine_user["email"]]
    if q.strip():
        like = f"%{q.strip()}%"
        where.append("(title ILIKE %s OR assignee ILIKE %s OR matter_no ILIKE %s OR notes ILIKE %s)")
        params += [like] * 4
    if matter.strip():
        where.append("matter_no ILIKE %s")
        params.append(f"%{matter.strip()}%")
    return where, params


def fetch_tasks(q: str, matter: str, urgency: str, sort: str, desc: bool, mine_user: dict | None = None) -> list[dict]:
    where, params = filter_sql(q, matter, mine_user)
    if urgency in COLORS:
        where.append("color = %s")
        params.append(urgency)
    order = SORT_FIELD.get(sort, "deadline")
    direction = "DESC" if desc else "ASC"
    sql = ("SELECT todos.*, (SELECT count(*) FROM task_comments c WHERE c.todo_id = todos.id) AS comment_count "
           "FROM todos")
    if where:
        sql += " WHERE " + " AND ".join(where)
    sql += f" ORDER BY {order} {direction} NULLS LAST, lower(title) ASC"
    with pool.connection() as conn:
        return conn.execute(sql, params).fetchall()


@app.get(P + "/tasks", response_class=HTMLResponse)
def list_tasks(request: Request, q: str = "", matter: str = "", urgency: str = "all", mine: str = "",
               sort: str = "deadline", desc: str = "0", view: str = "list", month: str = "", day: str = "",
               who: str = "", user: dict = Depends(require_user)):
    if view == "activity":
        return activity_view(request, day, who)
    if view == "bin":
        return bin_view(request)
    mine_user = user if mine == "1" else None
    rows = fetch_tasks(q, matter, urgency, sort, desc == "1", mine_user)
    where, params = filter_sql(q, matter, mine_user)
    sql = "SELECT color, count(*) AS n FROM todos" + (" WHERE " + " AND ".join(where) if where else "") + " GROUP BY color"
    with pool.connection() as conn:
        counts = {r["color"]: r["n"] for r in conn.execute(sql, params).fetchall()}
    filtered = bool(q.strip() or matter.strip() or urgency in COLORS or mine_user)
    if view == "calendar":
        return render(request, "partials/calendar.html", counts=counts, urgency=urgency, total=sum(counts.values()),
                      mine=bool(mine_user), filtered=filtered, **calendar_context(rows, month))
    return render(request, "partials/table.html", rows=rows, sort=sort, desc=desc == "1", filtered=filtered,
                  counts=counts, urgency=urgency, total=sum(counts.values()), mine=bool(mine_user))


def calendar_context(rows: list[dict], month: str) -> dict:
    try:
        first = datetime.strptime(month, "%Y-%m").date()
    except ValueError:
        first = today_local().replace(day=1)
    weeks = calendar.Calendar(firstweekday=0).monthdatescalendar(first.year, first.month)
    by_day: dict[date, list[dict]] = {}
    for r in rows:
        if r["deadline"] and weeks[0][0] <= r["deadline"] <= weeks[-1][-1]:
            by_day.setdefault(r["deadline"], []).append(r)
    rank = {c: i for i, c in enumerate(reversed(COLOR_ORDER))}
    for items in by_day.values():
        items.sort(key=lambda t: (rank.get(t["color"], 9), t["title"].lower()))
    prev_month = (first - timedelta(days=1)).replace(day=1)
    next_month = (first + timedelta(days=32)).replace(day=1)
    return {"first": first, "weeks": weeks, "by_day": by_day, "today": today_local(),
            "prev_month": prev_month.strftime("%Y-%m"), "next_month": next_month.strftime("%Y-%m"),
            "this_month": today_local().strftime("%Y-%m"), "undated": [r for r in rows if not r["deadline"]],
            "earlier_overdue": [r for r in rows if r["deadline"] and r["deadline"] < min(weeks[0][0], today_local())],
            "in_month": sum(len(items) for d, items in by_day.items() if d.month == first.month)}


BIN_DAYS = 30


def bin_view(request: Request):
    with pool.connection() as conn:
        entries = conn.execute(
            f"""SELECT * FROM todo_history WHERE field='deleted' AND snapshot IS NOT NULL AND restored_at IS NULL
                AND changed_at >= now() - interval '{BIN_DAYS} days' ORDER BY changed_at DESC, id DESC LIMIT 500"""
        ).fetchall()
    return render(request, "partials/bin.html", entries=entries, tz=TEAM_TZ, days=BIN_DAYS)


@app.post(P + "/tasks/bulk")
def bulk_update(ids: str = Form(""), action: str = Form(""), value: str = Form(""), user: dict = Depends(require_user)):
    try:
        task_ids = sorted({int(i) for i in ids.split(",") if i.strip()})
    except ValueError:
        return Response("Bad ids", status_code=400)
    if not task_ids or len(task_ids) > 1000:
        return Response("Choose between 1 and 1000 tasks", status_code=400)
    if action == "color":
        if value not in COLORS:
            return Response("Bad urgency", status_code=400)
        new, label = value, COLORS[value]["label"]
    elif action == "assignee":
        new = one_line(value)
        label = f"assignee {new}" if new else "no assignee"
    elif action == "deadline":
        due = parse_deadline(value)
        if due is None:
            return Response("Bad date", status_code=400)
        new = due or None
        label = due.strftime("%a %d %b %Y") if due else "no deadline"
    else:
        return Response("Bad action", status_code=400)
    field = {"color": "color", "assignee": "assignee", "deadline": "deadline"}[action]
    changed_count = 0
    with pool.connection() as conn:
        with conn.transaction():
            rows = conn.execute(f"SELECT id, title, {field} FROM todos WHERE id = ANY(%s) ORDER BY id FOR UPDATE",
                                (task_ids,)).fetchall()
            for row in rows:
                if row[field] == new:
                    continue
                conn.execute(f"UPDATE todos SET {field}=%s, updated_at=now(), updated_by=%s WHERE id=%s",
                             (new, user["name"], row["id"]))
                log_changes(conn, row["id"], row, {field: new}, user["name"])
                changed_count += 1
    missing = len(task_ids) - len(rows)
    msg = f"Set {changed_count} task{'s' if changed_count != 1 else ''} to {label}"
    if missing:
        msg += f" ({missing} no longer exist{'s' if missing == 1 else ''})"
    return changed({"toast": msg, "bulkDone": True})


def activity_view(request: Request, day: str, who: str):
    chosen = parse_deadline(day) or today_local()
    if not 2000 <= chosen.year <= 2100:
        chosen = today_local()
    start = datetime.combine(chosen, datetime.min.time(), TEAM_TZ)
    params = [start, start + timedelta(days=1)]
    sql = ("SELECT h.*, t.title AS current_title FROM todo_history h LEFT JOIN todos t ON t.id = h.todo_id "
           "WHERE h.changed_at >= %s AND h.changed_at < %s")
    if who.strip():
        sql += " AND h.changed_by = %s"
        params.append(who.strip())
    with pool.connection() as conn:
        entries = conn.execute(sql + " ORDER BY h.changed_at DESC, h.id DESC LIMIT 500", params).fetchall()
        people = [r["changed_by"] for r in conn.execute(
            "SELECT DISTINCT changed_by FROM todo_history WHERE changed_by <> '' ORDER BY changed_by").fetchall()]
    return render(request, "partials/activity.html", entries=entries, labels=TRACKED, day=chosen, tz=TEAM_TZ,
                  is_today=chosen == today_local(), who=who.strip(), people=people,
                  prev_day=(chosen - timedelta(days=1)).isoformat(), next_day=(chosen + timedelta(days=1)).isoformat())


def read_task_form(form) -> tuple[dict, dict]:
    errors = {}
    title = one_line(form.get("title", ""))
    if not title:
        errors["title"] = "Please enter a task title."
    deadline = parse_deadline(form.get("deadline", ""))
    if deadline is None:
        errors["deadline"] = "Deadline must be blank or in YYYY-MM-DD format."
    url = normalize_url(form.get("hyperlink", ""))
    if url is None:
        errors["hyperlink"] = "Hyperlink must be a valid http, https, mailto, or local file URL."
    color = form.get("color", "green")
    data = {
        "title": title,
        "assignee": one_line(form.get("assignee", "")),
        "matter_no": one_line(form.get("matter_no", "")),
        "deadline": deadline or None,
        "color": color if color in COLORS else "green",
        "hyperlink": url or "",
        "notes": (form.get("notes", "") or "").strip(),
    }
    return data, errors


TRACKED = {"title": "Task", "assignee": "Assignee", "matter_no": "Matter No", "deadline": "Deadline",
           "color": "Urgency", "hyperlink": "Hyperlink", "notes": "Notes"}


def display_value(field: str, value) -> str:
    if field == "color":
        return COLORS[value]["label"] if value in COLORS else (value or "")
    if field == "deadline":
        return value.isoformat() if value else ""
    return value or ""


def log_changes(conn, todo_id: int, before: dict, after: dict, by: str) -> None:
    title = after.get("title") or before.get("title", "")
    rows = []
    for field in TRACKED:
        if field not in after:
            continue
        old, new = display_value(field, before.get(field)), display_value(field, after.get(field))
        if old != new:
            rows.append((todo_id, title, by, field, old, new))
    if rows:
        with conn.cursor() as cur:
            cur.executemany("INSERT INTO todo_history (todo_id, task_title, changed_by, field, old_value, new_value) "
                            "VALUES (%s, %s, %s, %s, %s, %s)", rows)


INSERT_TODO = """INSERT INTO todos (title, assignee, matter_no, deadline, color, hyperlink, notes, updated_at, updated_by)
    VALUES (%(title)s, %(assignee)s, %(matter_no)s, %(deadline)s, %(color)s, %(hyperlink)s, %(notes)s, now(), %(by)s)
    RETURNING id"""


def insert_todo(conn, data: dict, by: str, how: str = "created") -> None:
    new_id = conn.execute(INSERT_TODO, {**data, "by": by}).fetchone()["id"]
    conn.execute("INSERT INTO todo_history (todo_id, task_title, changed_by, field) VALUES (%s, %s, %s, %s)",
                 (new_id, data["title"], by, how))


def people_names() -> list[str]:
    with pool.connection() as conn:
        return [r["name"] for r in conn.execute("SELECT DISTINCT name FROM users ORDER BY name").fetchall()]


def render_form(request: Request, task: dict, task_id: int | None, errors: dict):
    return render(request, "partials/form.html", task=task, task_id=task_id, errors=errors, people=people_names())


def get_task(task_id: int) -> dict | None:
    with pool.connection() as conn:
        return conn.execute("SELECT * FROM todos WHERE id=%s", (task_id,)).fetchone()


def form_values(task: dict) -> dict:
    return {**task, "deadline": task["deadline"].isoformat() if task.get("deadline") else ""}


@app.get(P + "/tasks/new", response_class=HTMLResponse)
def new_task_form(request: Request, deadline: str = "", _user: dict = Depends(require_user)):
    due = parse_deadline(deadline)
    return render_form(request, {"color": "green", "deadline": due.isoformat() if due else ""}, None, {})


@app.get(P + "/tasks/{task_id}/edit", response_class=HTMLResponse)
def edit_task_form(request: Request, task_id: int, _user: dict = Depends(require_user)):
    task = get_task(task_id)
    if task is None:
        return HTMLResponse(GONE)
    return render_form(request, form_values(task), task_id, {})


COMMENT_MAX = 1000


def render_comments(request: Request, task_id: int, user: dict, error: str = ""):
    with pool.connection() as conn:
        comments = conn.execute("SELECT * FROM task_comments WHERE todo_id=%s ORDER BY created_at, id",
                                (task_id,)).fetchall()
    return render(request, "partials/comments.html", comments=comments, task_id=task_id, me=user, tz=TEAM_TZ,
                  error=error, max_len=COMMENT_MAX)


@app.get(P + "/tasks/{task_id}/comments", response_class=HTMLResponse)
def list_comments(request: Request, task_id: int, user: dict = Depends(require_user)):
    return render_comments(request, task_id, user)


@app.post(P + "/tasks/{task_id}/comments", response_class=HTMLResponse)
def add_comment(request: Request, task_id: int, body: str = Form(""), user: dict = Depends(require_user)):
    text = body.strip()
    if not text:
        return render_comments(request, task_id, user, "Write a comment first.")
    if len(text) > COMMENT_MAX:
        return render_comments(request, task_id, user, f"Comments can be up to {COMMENT_MAX} characters.")
    with pool.connection() as conn:
        with conn.transaction():
            task = conn.execute("SELECT title FROM todos WHERE id=%s", (task_id,)).fetchone()
            if not task:
                return HTMLResponse(GONE)
            conn.execute("INSERT INTO task_comments (todo_id, user_id, author_name, body) VALUES (%s, %s, %s, %s)",
                         (task_id, user["id"], user["name"], text))
            conn.execute("INSERT INTO todo_history (todo_id, task_title, changed_by, field, new_value) "
                         "VALUES (%s, %s, %s, 'comment', %s)", (task_id, task["title"], user["name"], text))
    resp = render_comments(request, task_id, user)
    resp.headers["HX-Trigger"] = json.dumps({"commentsChanged": True, "historyChanged": True})
    return resp


@app.delete(P + "/comments/{comment_id}", response_class=HTMLResponse)
def delete_comment(request: Request, comment_id: int, user: dict = Depends(require_user)):
    with pool.connection() as conn:
        row = conn.execute("SELECT todo_id, user_id FROM task_comments WHERE id=%s", (comment_id,)).fetchone()
        if not row:
            return Response("Not found", status_code=404)
        if row["user_id"] != user["id"] and not user["is_admin"]:
            return Response("Only the author or an admin can remove a comment", status_code=403)
        conn.execute("DELETE FROM task_comments WHERE id=%s", (comment_id,))
    resp = render_comments(request, row["todo_id"], user)
    resp.headers["HX-Trigger"] = json.dumps({"commentsChanged": True})
    return resp


@app.get(P + "/print", response_class=HTMLResponse)
def print_sheet(request: Request, q: str = "", matter: str = "", urgency: str = "all", mine: str = "",
                sort: str = "deadline", desc: str = "0", comments: str = "", user: dict = Depends(require_user)):
    mine_user = user if mine == "1" else None
    rows = fetch_tasks(q, matter, urgency, sort, desc == "1", mine_user)
    by_task: dict[int, list[dict]] = {}
    if comments == "1" and rows:
        with pool.connection() as conn:
            for c in conn.execute("SELECT * FROM task_comments WHERE todo_id = ANY(%s) ORDER BY created_at, id",
                                  ([r["id"] for r in rows],)).fetchall():
                by_task.setdefault(c["todo_id"], []).append(c)
    params = {"q": q.strip(), "matter": matter.strip(), "urgency": urgency, "mine": "1" if mine_user else "",
              "sort": sort, "desc": desc}
    return render(request, "print.html", user=user, rows=rows, tz=TEAM_TZ, comments=by_task, show_comments=comments == "1",
                  description=describe_filter(params), printed_at=datetime.now(TEAM_TZ),
                  query=urlencode({k: v for k, v in params.items() if v}))


@app.get(P + "/tasks/{task_id}/history", response_class=HTMLResponse)
def task_history(request: Request, task_id: int, _user: dict = Depends(require_user)):
    with pool.connection() as conn:
        entries = conn.execute("SELECT * FROM todo_history WHERE todo_id=%s ORDER BY changed_at DESC, id DESC LIMIT 200",
                               (task_id,)).fetchall()
    return render(request, "partials/history.html", entries=entries, labels=TRACKED, tz=TEAM_TZ)


async def task_form(request: Request) -> dict:
    return dict(await request.form())


GONE = '<p class="form-error" data-testid="task-missing">This task was deleted by someone else.</p>'


@app.post(P + "/tasks", response_class=HTMLResponse)
def create_task(request: Request, form: dict = Depends(task_form), user: dict = Depends(require_user)):
    data, errors = read_task_form(form)
    if errors:
        return render_form(request, form, None, errors)
    with pool.connection() as conn:
        with conn.transaction():
            insert_todo(conn, data, user["name"])
    return changed({"toast": "Task added"})


@app.post(P + "/tasks/{task_id}", response_class=HTMLResponse)
def update_task(request: Request, task_id: int, form: dict = Depends(task_form), user: dict = Depends(require_user)):
    data, errors = read_task_form(form)
    if errors:
        return render_form(request, form, task_id, errors)
    with pool.connection() as conn:
        with conn.transaction():
            before = conn.execute("SELECT * FROM todos WHERE id=%s FOR UPDATE", (task_id,)).fetchone()
            if before:
                conn.execute(
                    """UPDATE todos SET title=%(title)s, assignee=%(assignee)s, matter_no=%(matter_no)s, deadline=%(deadline)s,
                       color=%(color)s, hyperlink=%(hyperlink)s, notes=%(notes)s, updated_at=now(), updated_by=%(by)s
                       WHERE id=%(id)s""",
                    {**data, "by": user["name"], "id": task_id},
                )
                log_changes(conn, task_id, before, data, user["name"])
    if before is None:
        return HTMLResponse(GONE, headers={"HX-Trigger": json.dumps({"tasksChanged": True, "toast": "That task was deleted"})})
    return changed({"toast": "Task saved"})


@app.post(P + "/tasks/{task_id}/color")
def set_color(task_id: int, color: str = Form(...), user: dict = Depends(require_user)):
    if color not in COLORS:
        return Response("Unknown color", status_code=400)
    with pool.connection() as conn:
        with conn.transaction():
            before = conn.execute("SELECT color, title FROM todos WHERE id=%s FOR UPDATE", (task_id,)).fetchone()
            if before and before["color"] != color:
                conn.execute("UPDATE todos SET color=%s, updated_at=now(), updated_by=%s WHERE id=%s",
                             (color, user["name"], task_id))
                log_changes(conn, task_id, before, {"color": color}, user["name"])
    return changed(None if before else {"toast": "That task was deleted"})


@app.delete(P + "/tasks/{task_id}")
def delete_task(task_id: int, user: dict = Depends(require_user)):
    with pool.connection() as conn:
        with conn.transaction():
            delete_with_snapshot(conn, task_id, user["name"])
    return changed({"toast": "Task deleted · restore it from the Recycle bin"})


def delete_with_snapshot(conn, task_id: int, by: str) -> bool:
    gone = conn.execute("DELETE FROM todos WHERE id=%s RETURNING *", (task_id,)).fetchone()
    if gone:
        snap = {f: display_value(f, gone[f]) if f == "deadline" else gone[f] for f in TRACKED}
        conn.execute(
            """INSERT INTO todo_history (todo_id, orig_todo_id, task_title, changed_by, field, snapshot)
               VALUES (NULL, %s, %s, %s, 'deleted', %s)""",
            (task_id, gone["title"], by, Jsonb(snap)),
        )
    return bool(gone)


@app.post(P + "/bulk-delete")
def bulk_delete(ids: str = Form(""), user: dict = Depends(require_user)):
    try:
        task_ids = sorted({int(i) for i in ids.split(",") if i.strip()})
    except ValueError:
        return Response("Bad ids", status_code=400)
    if not task_ids or len(task_ids) > 1000:
        return Response("Choose between 1 and 1000 tasks", status_code=400)
    with pool.connection() as conn:
        with conn.transaction():
            count = sum(delete_with_snapshot(conn, tid, user["name"]) for tid in task_ids)
    return changed({"toast": f"Deleted {count} task{'s' if count != 1 else ''} · restore from the Recycle bin",
                    "bulkDone": True})


# ---------- saved filters ----------

FILTER_KEYS = ("q", "matter", "urgency", "mine", "sort", "desc")
MAX_SAVED_FILTERS = 20


@app.get(P + "/filters", response_class=HTMLResponse)
def list_filters(request: Request, user: dict = Depends(require_user)):
    with pool.connection() as conn:
        saved = conn.execute(VISIBLE_FILTERS_SQL + " ORDER BY (f.user_id = %(me)s) DESC, lower(f.name)",
                             {"me": user["id"]}).fetchall()
        default_id = conn.execute("SELECT default_filter_id FROM users WHERE id=%s", (user["id"],)).fetchone()["default_filter_id"]
    return render(request, "partials/saved_filters.html", saved=saved, describe=describe_filter,
                  default_id=default_id, me=user)


VISIBLE_FILTERS_SQL = """SELECT f.id, f.name, f.params, f.shared, f.user_id, u.name AS owner_name
    FROM saved_filters f JOIN users u ON u.id = f.user_id
    WHERE (f.user_id = %(me)s OR f.shared)"""


def default_filter(user: dict) -> dict | None:
    with pool.connection() as conn:
        return conn.execute(VISIBLE_FILTERS_SQL + " AND f.id = (SELECT default_filter_id FROM users WHERE id = %(me)s)",
                            {"me": user["id"]}).fetchone()


def filter_event(toast: str) -> Response:
    return Response(headers={"HX-Trigger": json.dumps({"filtersSaved": True, "toast": toast}), "HX-Reswap": "none"})


@app.post(P + "/filters/{filter_id}/share")
def toggle_share(filter_id: int, user: dict = Depends(require_admin)):
    with pool.connection() as conn:
        row = conn.execute("UPDATE saved_filters SET shared = NOT shared WHERE id=%s AND user_id=%s RETURNING name, shared",
                           (filter_id, user["id"])).fetchone()
        if row and not row["shared"]:
            conn.execute("UPDATE users SET default_filter_id=NULL WHERE default_filter_id=%s AND id<>%s",
                         (filter_id, user["id"]))
    if not row:
        return Response("Not found", status_code=404)
    return filter_event(f"“{row['name']}” is now {'shared with the team' if row['shared'] else 'private'}")


@app.post(P + "/filters/{filter_id}/default")
def toggle_default(filter_id: int, user: dict = Depends(require_user)):
    with pool.connection() as conn:
        with conn.transaction():
            row = conn.execute(VISIBLE_FILTERS_SQL + " AND f.id = %(id)s", {"me": user["id"], "id": filter_id}).fetchone()
            if not row:
                return Response("Not found", status_code=404)
            current = conn.execute("SELECT default_filter_id FROM users WHERE id=%s FOR UPDATE", (user["id"],)).fetchone()
            new = None if current["default_filter_id"] == filter_id else filter_id
            conn.execute("UPDATE users SET default_filter_id=%s WHERE id=%s", (new, user["id"]))
    return filter_event(f"“{row['name']}” will open when you sign in" if new else "No filter opens automatically now")


def describe_filter(params: dict) -> str:
    parts = []
    if params.get("q"):
        parts.append(f"search “{params['q']}”")
    if params.get("matter"):
        parts.append(f"matter “{params['matter']}”")
    if params.get("urgency") in COLORS:
        parts.append(COLORS[params["urgency"]]["label"])
    if params.get("mine") == "1":
        parts.append("my tasks")
    sort = dict(HEADINGS).get(params.get("sort"), "Deadline")
    parts.append(f"sorted by {sort}{' (reversed)' if params.get('desc') == '1' else ''}")
    return " · ".join(parts)


@app.post(P + "/filters")
async def save_filter(request: Request, user: dict = Depends(require_user)):
    form = await request.form()
    name = one_line(form.get("name", ""))[:60]
    if not name:
        return Response("Name required", status_code=400)
    params = {k: str(form.get(k, "")).strip()[:200] for k in FILTER_KEYS}
    if params["urgency"] not in COLORS:
        params["urgency"] = "all"
    params["mine"] = "1" if params["mine"] == "1" else ""
    params["desc"] = "1" if params["desc"] == "1" else "0"
    if params["sort"] not in SORT_FIELD:
        params["sort"] = "deadline"
    return await run_in_threadpool(store_filter, user["id"], name, params)


def store_filter(user_id: int, name: str, params: dict):
    with pool.connection() as conn:
        with conn.transaction():
            conn.execute("SELECT pg_advisory_xact_lock(%s)", (user_id,))
            exists = conn.execute("SELECT 1 FROM saved_filters WHERE user_id=%s AND lower(name)=lower(%s)",
                                  (user_id, name)).fetchone()
            count = conn.execute("SELECT count(*) AS n FROM saved_filters WHERE user_id=%s", (user_id,)).fetchone()["n"]
            if not exists and count >= MAX_SAVED_FILTERS:
                return Response(f"You can save up to {MAX_SAVED_FILTERS} filters", status_code=400)
            conn.execute(
                """INSERT INTO saved_filters (user_id, name, params) VALUES (%s, %s, %s)
                   ON CONFLICT (user_id, lower(name)) DO UPDATE SET params = EXCLUDED.params, name = EXCLUDED.name""",
                (user_id, name, Jsonb(params)),
            )
    verb = "Updated" if exists else "Saved"
    return Response(headers={"HX-Trigger": json.dumps({"filtersSaved": True, "toast": f"{verb} filter “{name}”"}),
                             "HX-Reswap": "none"})


@app.delete(P + "/filters/{filter_id}")
def delete_filter(filter_id: int, user: dict = Depends(require_user)):
    with pool.connection() as conn:
        conn.execute("DELETE FROM saved_filters WHERE id=%s AND user_id=%s", (filter_id, user["id"]))
    return filter_event("Filter removed")


@app.post(P + "/history/{entry_id}/restore")
def restore_task(entry_id: int, user: dict = Depends(require_user)):
    with pool.connection() as conn:
        with conn.transaction():
            entry = conn.execute("SELECT * FROM todo_history WHERE id=%s AND field='deleted' FOR UPDATE",
                                 (entry_id,)).fetchone()
            if not entry or not entry["snapshot"]:
                return changed({"toast": "Nothing to restore"})
            if entry["restored_at"]:
                return changed({"toast": "This task was already restored"})
            data = {**entry["snapshot"], "deadline": entry["snapshot"].get("deadline") or None, "by": user["name"]}
            old_id = entry["orig_todo_id"]
            taken = old_id is None or conn.execute("SELECT 1 FROM todos WHERE id=%s", (old_id,)).fetchone()
            cols = "title, assignee, matter_no, deadline, color, hyperlink, notes, updated_at, updated_by"
            vals = "%(title)s, %(assignee)s, %(matter_no)s, %(deadline)s, %(color)s, %(hyperlink)s, %(notes)s, now(), %(by)s"
            if taken:
                new_id = conn.execute(f"INSERT INTO todos ({cols}) VALUES ({vals}) RETURNING id", data).fetchone()["id"]
            else:
                new_id = conn.execute(f"INSERT INTO todos (id, {cols}) VALUES (%(id)s, {vals}) RETURNING id",
                                      {**data, "id": old_id}).fetchone()["id"]
                conn.execute("UPDATE todo_history SET todo_id=%s WHERE orig_todo_id=%s AND todo_id IS NULL", (new_id, old_id))
            conn.execute("UPDATE todo_history SET restored_at=now() WHERE id=%s", (entry_id,))
            if data["deadline"] and data["deadline"] < today_local().isoformat():
                conn.execute("INSERT INTO overdue_alerts (todo_id, deadline) VALUES (%s, %s) ON CONFLICT DO NOTHING",
                             (new_id, data["deadline"]))
            conn.execute("INSERT INTO todo_history (todo_id, task_title, changed_by, field) VALUES (%s, %s, %s, 'restored')",
                         (new_id, data["title"], user["name"]))
    return changed({"toast": f"Restored “{data['title']}”"})


@app.post(P + "/tasks/{task_id}/deadline")
def move_deadline(task_id: int, deadline: str = Form(""), user: dict = Depends(require_user)):
    due = parse_deadline(deadline)
    if due is None:
        return Response("Bad date", status_code=400)
    with pool.connection() as conn:
        with conn.transaction():
            before = conn.execute("SELECT deadline, title FROM todos WHERE id=%s FOR UPDATE", (task_id,)).fetchone()
            moved = bool(before) and before["deadline"] != (due or None)
            if moved:
                conn.execute("UPDATE todos SET deadline=%s, updated_at=now(), updated_by=%s WHERE id=%s",
                             (due or None, user["name"], task_id))
                log_changes(conn, task_id, before, {"deadline": due or None}, user["name"])
    if not before:
        return changed({"toast": "That task was deleted"})
    if not moved:
        return changed()
    return changed({"toast": f"Moved “{before['title']}” to {due.strftime('%a %d %b') if due else 'no deadline'}"})


# ---------- CSV export / import ----------

CSV_HEADERS = ["Task", "Assignee", "Matter No", "Deadline", "Urgency", "Hyperlink", "Notes", "Updated At", "Updated By"]
HEADER_ALIASES = {
    "task": "title", "title": "title", "assignee": "assignee",
    "matter no": "matter_no", "matter_no": "matter_no", "matter": "matter_no", "matter number": "matter_no",
    "deadline": "deadline", "due": "deadline", "due date": "deadline",
    "urgency": "color", "color": "color", "colour": "color", "status": "color",
    "hyperlink": "hyperlink", "link": "hyperlink", "url": "hyperlink", "notes": "notes",
}


def safe_cell(value) -> str:
    text = "" if value is None else str(value)
    return "'" + text if text[:1] in ("=", "+", "-", "@", "\t", "\r") else text


@app.get(P + "/export.csv")
def export_csv(_user: dict = Depends(require_user)):
    rows = fetch_tasks("", "", "all", "deadline", False)
    buf = io.StringIO()
    writer = csv.writer(buf)
    writer.writerow(CSV_HEADERS)
    for r in rows:
        writer.writerow([safe_cell(v) for v in [
            r["title"], r["assignee"], r["matter_no"], r["deadline"].isoformat() if r["deadline"] else "",
            COLORS.get(r["color"], COLORS["green"])["label"], r["hyperlink"], r["notes"],
            r["updated_at"].astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"), r["updated_by"],
        ]])
    stamp = today_local().isoformat()
    return Response("\ufeff" + buf.getvalue(), media_type="text/csv",
                    headers={"Content-Disposition": f'attachment; filename="deadlines-{stamp}.csv"'})


class ImportFileError(Exception):
    pass


def parse_import(text: str) -> tuple[list[dict], list[str]]:
    reader = csv.reader(io.StringIO(text))
    try:
        header = next(reader)
    except StopIteration:
        raise ImportFileError("The file is empty.")
    fields = [HEADER_ALIASES.get(h.strip().lower()) for h in header]
    if "title" not in fields:
        raise ImportFileError('No "Task" (or "Title") column found in the first row.')
    records, errors = [], []
    for line_no, raw in enumerate(reader, start=2):
        if not any(cell.strip() for cell in raw):
            continue
        values = {f: raw[i] for i, f in enumerate(fields) if f and i < len(raw)}
        values = {k: v[1:] if v[:2] in ("'=", "'+", "'-", "'@") else v for k, v in values.items()}
        title = one_line(values.get("title", ""))
        deadline = parse_deadline(values.get("deadline", ""))
        url = normalize_url(values.get("hyperlink", ""))
        color = color_from(values.get("color", ""))
        problem = None
        if not title:
            problem = "missing task title"
        elif deadline is None:
            problem = f'bad deadline "{values.get("deadline", "").strip()}" (use YYYY-MM-DD)'
        elif url is None:
            problem = "hyperlink is not a valid http, https, mailto or file link"
        elif color is None:
            problem = f'unknown urgency "{values.get("color", "").strip()}"'
        if problem:
            errors.append(f"Row {line_no}: {problem}")
            continue
        records.append({
            "title": title, "assignee": one_line(values.get("assignee", "")),
            "matter_no": one_line(values.get("matter_no", "")), "deadline": deadline or None,
            "color": color, "hyperlink": url or "", "notes": (values.get("notes", "") or "").strip(),
        })
    return records, errors


@app.post(P + "/import", response_class=HTMLResponse)
async def import_csv(request: Request, file: UploadFile = File(...), user: dict = Depends(require_user)):
    content = await file.read(5 * 1024 * 1024 + 1)
    if len(content) > 5 * 1024 * 1024:
        return render(request, "partials/import_result.html", imported=0, errors=[], file_error="File is larger than 5 MB.")
    try:
        text = content.decode("utf-8-sig")
    except UnicodeDecodeError:
        text = content.decode("cp1252", errors="replace")
    try:
        records, errors = parse_import(text)
    except ImportFileError as exc:
        return render(request, "partials/import_result.html", imported=0, errors=[], file_error=str(exc))
    if records:
        await run_in_threadpool(insert_records, records, user["name"])
    headers = {"HX-Trigger": json.dumps({"tasksChanged": True})} if records else None
    return render(request, "partials/import_result.html", headers=headers, imported=len(records), errors=errors,
                  file_error=None)


def insert_records(records: list[dict], by: str) -> None:
    with pool.connection() as conn:
        with conn.transaction():
            for r in records:
                insert_todo(conn, r, by, "imported")


# ---------- admin: approved emails ----------

def admin_context(error: str | None = None) -> dict:
    with pool.connection() as conn:
        people = conn.execute(
            """SELECT a.email, a.added_at, a.added_by, u.name, u.created_at AS joined_at
               FROM approved_emails a LEFT JOIN users u ON u.email = a.email ORDER BY a.added_at DESC"""
        ).fetchall()
        admins = conn.execute("SELECT email, name FROM users WHERE is_admin ORDER BY email").fetchall()
        last_run = conn.execute("SELECT * FROM cron_runs WHERE kind='reminders' ORDER BY received_at DESC LIMIT 1").fetchone()
        last_digest = conn.execute("SELECT * FROM cron_runs WHERE kind='digest' ORDER BY received_at DESC LIMIT 1").fetchone()
        last_overdue = conn.execute("SELECT * FROM cron_runs WHERE kind='overdue' ORDER BY received_at DESC LIMIT 1").fetchone()
    return {"people": people, "admins": admins, "error": error, "smtp_ready": smtp_configured(),
            "last_run": last_run, "last_overdue": last_overdue, "last_digest": last_digest, "notice": None, "email_error": None}


@app.get(P + "/admin", response_class=HTMLResponse)
def admin_page(request: Request, notice: str = "", email_error: str = "", user: dict = Depends(require_admin)):
    ctx = admin_context()
    ctx.update(notice=notice[:300] or None, email_error=email_error[:500] or None)
    return render(request, "admin.html", user=user, **ctx)


@app.post(P + "/admin/approved", response_class=HTMLResponse)
def approve_email(request: Request, email: str = Form(""), user: dict = Depends(require_admin)):
    email = email.strip().lower()
    if not _EMAIL_RE.match(email):
        return render(request, "admin.html", status_code=400, user=user, **admin_context("Please enter a valid email."))
    with pool.connection() as conn:
        conn.execute("INSERT INTO approved_emails (email, added_by) VALUES (%s, %s) ON CONFLICT DO NOTHING",
                     (email, user["name"]))
    return RedirectResponse(f"{P}/admin", status_code=303)


@app.post(P + "/admin/revoke")
def revoke_email(email: str = Form(""), _user: dict = Depends(require_admin)):
    email = email.strip().lower()
    with pool.connection() as conn:
        conn.execute("DELETE FROM approved_emails WHERE email=%s", (email,))
        conn.execute("DELETE FROM users WHERE email=%s AND NOT is_admin", (email,))
    return RedirectResponse(f"{P}/admin", status_code=303)


# ---------- morning reminder emails ----------

REMINDER_COLORS = ("red", "orange", "yellow")
REMINDER_SCHEDULE = "every day at 7:00 AM (America/New_York)"
templates.env.globals.update(REMINDER_SCHEDULE=REMINDER_SCHEDULE)


def smtp_configured() -> bool:
    return all(os.environ.get(k, "").strip() for k in ("SMTP_HOST", "SMTP_PORT", "SMTP_FROM"))


def reminder_tasks(conn, user: dict) -> list[dict]:
    return conn.execute(
        f"""SELECT * FROM todos WHERE color = ANY(%s) AND {MINE_SQL}
            ORDER BY array_position(ARRAY['red','orange','yellow'], color), deadline NULLS LAST, lower(title)""",
        (list(REMINDER_COLORS), user["name"], user["email"]),
    ).fetchall()


def build_reminder(user: dict, tasks: list[dict], app_url: str) -> EmailMessage:
    groups = [(c, [t for t in tasks if t["color"] == c]) for c in REMINDER_COLORS]
    ctx = {"user": user, "groups": groups, "app_url": app_url, "count": len(tasks), "today": today_local()}
    msg = EmailMessage()
    msg["Subject"] = f"Your deadlines for {today_local():%a %d %b}: {len(tasks)} need attention"
    msg["From"] = os.environ["SMTP_FROM"]
    msg["To"] = user["email"]
    msg.set_content(templates.get_template("emails/reminder.txt").render(ctx))
    msg.add_alternative(templates.get_template("emails/reminder.html").render(ctx), subtype="html")
    return msg


def send_email(msg: EmailMessage) -> None:
    host, port = os.environ["SMTP_HOST"].strip(), int(os.environ["SMTP_PORT"])
    username, password = os.environ.get("SMTP_USERNAME", ""), os.environ.get("SMTP_PASSWORD", "")
    if port == 465:
        server = smtplib.SMTP_SSL(host, port, timeout=30)
    else:
        server = smtplib.SMTP(host, port, timeout=30)
        server.ehlo()
        if server.has_extn("starttls"):
            server.starttls()
            server.ehlo()
    with server:
        if username:
            server.login(username, password)
        server.send_message(msg)


def send_reminders(run_id: str, app_url: str) -> None:
    sent, failures = 0, []
    try:
        with pool.connection() as conn:
            users = conn.execute("SELECT id, email, name FROM users WHERE reminders_enabled ORDER BY id").fetchall()
            batches = [(u, reminder_tasks(conn, u)) for u in users]
        for user, tasks in batches:
            if not tasks:
                continue
            try:
                send_email(build_reminder(user, tasks, app_url))
                sent += 1
            except Exception as exc:
                log.exception("Reminder to %s failed", user["email"])
                failures.append(f"{user['email']}: {exc}")
    except Exception as exc:
        log.exception("Reminder run failed")
        failures.append(f"Run failed: {exc}")
    with pool.connection() as conn:
        conn.execute("UPDATE cron_runs SET sent=%s, error=%s WHERE run_id=%s",
                     (sent, "; ".join(failures)[:2000] or None, run_id))


def public_url(request: Request) -> str:
    host = (request.headers.get("x-forwarded-host") or request.headers.get("host", "")).split(",")[0].strip()
    return f"https://{host}{P}/"


def claim_run(run_id: str, kind: str) -> bool:
    with pool.connection() as conn:
        return conn.execute("INSERT INTO cron_runs (run_id, kind) VALUES (%s, %s) ON CONFLICT DO NOTHING RETURNING run_id",
                            (run_id, kind)).fetchone() is not None


async def accept_cron(request: Request, background: BackgroundTasks, kind: str, job):
    auth = request.headers.get("authorization", "")
    secret = os.environ["WEBHOOK_CRON_SECRET"]
    if not auth.startswith("Bearer ") or not hmac.compare_digest(auth[7:].encode(), secret.encode()):
        return Response(status_code=401)
    raw = await request.body()
    try:
        body = json.loads(raw) if raw.strip() else {}
    except ValueError:
        return Response("Invalid body", status_code=400)
    run_id = request.headers.get("x-webhook-id") or (body.get("run_id") if isinstance(body, dict) else None)
    if not run_id:
        return Response("Missing run id", status_code=400)
    if not await run_in_threadpool(claim_run, str(run_id), kind):
        return {"accepted": True, "duplicate": True}
    if not smtp_configured():
        await run_in_threadpool(record_run_error, str(run_id), "Email (SMTP) is not configured")
    else:
        background.add_task(job, str(run_id), public_url(request))
    return {"accepted": True}


@app.post(P + "/cron/reminders")
async def cron_reminders(request: Request, background: BackgroundTasks):
    # Cron endpoints must ack 2xx immediately; enqueue/background the actual work.
    return await accept_cron(request, background, "reminders", send_reminders)


@app.post(P + "/cron/overdue")
async def cron_overdue(request: Request, background: BackgroundTasks):
    # Cron endpoints must ack 2xx immediately; enqueue/background the actual work.
    return await accept_cron(request, background, "overdue", send_overdue_alerts)


def record_run_error(run_id: str, error: str) -> None:
    with pool.connection() as conn:
        conn.execute("UPDATE cron_runs SET sent=0, error=%s WHERE run_id=%s", (error, run_id))


@app.post(P + "/admin/test-reminder")
def test_reminder(request: Request, user: dict = Depends(require_admin)):
    if not smtp_configured():
        msg = {"email_error": "Email is not set up yet (SMTP details missing)."}
    else:
        with pool.connection() as conn:
            tasks = reminder_tasks(conn, user)
        try:
            send_email(build_reminder(user, tasks, public_url(request)))
            msg = {"notice": f"Test summary sent to {user['email']} ({len(tasks)} task{'s' if len(tasks) != 1 else ''})."}
        except Exception as exc:
            log.exception("Test reminder failed")
            msg = {"email_error": f"Sending failed: {exc}"}
    return RedirectResponse(f"{P}/admin?{urlencode(msg)}#email", status_code=303)


# ---------- overdue alerts ----------

OVERDUE_COLORS = ("red", "orange")
OVERDUE_LOOKBACK_DAYS = 14
templates.env.globals.update(OVERDUE_LOOKBACK_DAYS=OVERDUE_LOOKBACK_DAYS)


def matches(task: dict, user: dict) -> bool:
    who = task["assignee"].strip().lower()
    return bool(who) and who in (user["name"].strip().lower(), user["email"].strip().lower())


def build_overdue(user: dict, tasks: list[dict], app_url: str, assigned: bool) -> EmailMessage:
    ctx = {"user": user, "tasks": tasks, "app_url": app_url, "assigned": assigned}
    msg = EmailMessage()
    first = tasks[0]["title"]
    msg["Subject"] = f"Overdue: {first}" if len(tasks) == 1 else f"Overdue: {first} and {len(tasks) - 1} more"
    msg["From"] = os.environ["SMTP_FROM"]
    msg["To"] = user["email"]
    msg.set_content(templates.get_template("emails/overdue.txt").render(ctx))
    msg.add_alternative(templates.get_template("emails/overdue.html").render(ctx), subtype="html")
    return msg


def send_overdue_alerts(run_id: str, app_url: str) -> None:
    """Email assignees (or admins if nobody matches) once per task and deadline after the deadline passes."""
    sent, failures = 0, []
    try:
        today = today_local()
        with pool.connection() as conn:
            tasks = conn.execute(
                """SELECT t.* FROM todos t WHERE t.color = ANY(%s) AND t.deadline < %s AND t.deadline >= %s
                   AND NOT EXISTS (SELECT 1 FROM overdue_alerts a WHERE a.todo_id = t.id AND a.deadline = t.deadline)
                   ORDER BY t.deadline, lower(t.title)""",
                (list(OVERDUE_COLORS), today, today - timedelta(days=OVERDUE_LOOKBACK_DAYS)),
            ).fetchall()
            users = conn.execute("SELECT id, email, name, is_admin, reminders_enabled FROM users").fetchall()
        outbox: dict[tuple, dict] = {}
        unsent_ids = set()
        for task in tasks:
            owners = [u for u in users if matches(task, u)]
            if owners:  # owners who switched emails off get nothing; nobody else is told instead
                recipients = [u for u in owners if u["reminders_enabled"]]
            else:
                recipients = [u for u in users if u["is_admin"] and u["reminders_enabled"]]
                if not recipients:
                    unsent_ids.add(task["id"])
            for u in recipients:
                entry = outbox.setdefault((u["id"], bool(owners)), {"user": u, "tasks": [], "assigned": bool(owners)})
                entry["tasks"].append(task)
        failed_ids = set(unsent_ids)
        for entry in outbox.values():
            try:
                send_email(build_overdue(entry["user"], entry["tasks"], app_url, entry["assigned"]))
                sent += 1
            except Exception as exc:
                log.exception("Overdue alert to %s failed", entry["user"]["email"])
                failures.append(f"{entry['user']['email']}: {exc}")
                failed_ids.update(t["id"] for t in entry["tasks"])
        done = [(t["id"], t["deadline"]) for t in tasks if t["id"] not in failed_ids]
        if done:
            with pool.connection() as conn:
                with conn.cursor() as cur:
                    cur.executemany("INSERT INTO overdue_alerts (todo_id, deadline) VALUES (%s, %s) ON CONFLICT DO NOTHING",
                                    done)
    except Exception as exc:
        log.exception("Overdue run failed")
        failures.append(f"Run failed: {exc}")
    with pool.connection() as conn:
        conn.execute("UPDATE cron_runs SET sent=%s, error=%s WHERE run_id=%s",
                     (sent, "; ".join(failures)[:2000] or None, run_id))


@app.post(P + "/admin/check-overdue")
def check_overdue_now(request: Request, _user: dict = Depends(require_admin)):
    if not smtp_configured():
        msg = {"email_error": "Email is not set up yet (SMTP details missing)."}
    else:
        run_id = f"manual-{datetime.now(timezone.utc).isoformat()}"
        claim_run(run_id, "overdue")
        send_overdue_alerts(run_id, public_url(request))
        with pool.connection() as conn:
            run = conn.execute("SELECT sent, error FROM cron_runs WHERE run_id=%s", (run_id,)).fetchone()
        msg = ({"email_error": f"Some alerts failed: {run['error']}"} if run["error"]
               else {"notice": f"Overdue check done: {run['sent']} email(s) sent."})
    return RedirectResponse(f"{P}/admin?{urlencode(msg)}#email", status_code=303)


# ---------- weekly team digest ----------

DIGEST_SCHEDULE = "every Monday at 8:00 AM (America/New_York)"
templates.env.globals.update(DIGEST_SCHEDULE=DIGEST_SCHEDULE)


def digest_context(app_url: str) -> dict:
    today = today_local()
    since = datetime.now(TEAM_TZ) - timedelta(days=7)
    rank = "array_position(ARRAY['red','orange','yellow','blue','green'], color)"
    with pool.connection() as conn:
        by_field = {r["field"]: r["n"] for r in conn.execute(
            "SELECT field, count(*) AS n FROM todo_history WHERE changed_at >= %s GROUP BY field", (since,)).fetchall()}
        people = conn.execute(
            """SELECT changed_by, count(*) AS n FROM todo_history WHERE changed_at >= %s AND changed_by <> ''
               GROUP BY changed_by ORDER BY n DESC, changed_by""", (since,)).fetchall()
        busiest = conn.execute(
            """SELECT COALESCE(t.title, max(h.task_title)) AS title, (t.id IS NULL) AS gone, count(*) AS n,
                      string_agg(DISTINCT h.field, ',') AS fields
               FROM todo_history h LEFT JOIN todos t ON t.id = h.todo_id
               WHERE h.changed_at >= %s GROUP BY t.id, t.title, COALESCE(h.orig_todo_id, -h.id)
               ORDER BY n DESC, title LIMIT 15""", (since,)).fetchall()
        due_soon = conn.execute(
            f"SELECT * FROM todos WHERE deadline BETWEEN %s AND %s ORDER BY deadline, {rank}, lower(title)",
            (today, today + timedelta(days=6))).fetchall()
        overdue = conn.execute(
            f"SELECT * FROM todos WHERE deadline < %s AND color <> 'green' ORDER BY {rank}, deadline, lower(title)",
            (today,)).fetchall()
    return {"today": today, "since": since.date(), "total": sum(by_field.values()),
            "added": by_field.get("created", 0) + by_field.get("imported", 0), "deleted": by_field.get("deleted", 0),
            "restored": by_field.get("restored", 0), "people": people, "busiest": busiest, "labels": TRACKED,
            "due_soon": due_soon, "overdue": overdue, "app_url": app_url}


def build_digest(user: dict, ctx: dict) -> EmailMessage:
    ctx = {**ctx, "user": user}
    msg = EmailMessage()
    msg["Subject"] = (f"Weekly deadline digest: {len(ctx['due_soon'])} due this week, "
                      f"{len(ctx['overdue'])} overdue, {ctx['total']} changes")
    msg["From"] = os.environ["SMTP_FROM"]
    msg["To"] = user["email"]
    msg.set_content(templates.get_template("emails/digest.txt").render(ctx))
    msg.add_alternative(templates.get_template("emails/digest.html").render(ctx), subtype="html")
    return msg


def send_digest(run_id: str, app_url: str) -> None:
    sent, failures = 0, []
    try:
        ctx = digest_context(app_url)
        with pool.connection() as conn:
            admins = conn.execute("SELECT id, email, name FROM users WHERE is_admin AND reminders_enabled").fetchall()
        for admin in admins:
            try:
                send_email(build_digest(admin, ctx))
                sent += 1
            except Exception as exc:
                log.exception("Digest to %s failed", admin["email"])
                failures.append(f"{admin['email']}: {exc}")
    except Exception as exc:
        log.exception("Digest run failed")
        failures.append(f"Run failed: {exc}")
    with pool.connection() as conn:
        conn.execute("UPDATE cron_runs SET sent=%s, error=%s WHERE run_id=%s",
                     (sent, "; ".join(failures)[:2000] or None, run_id))


@app.post(P + "/cron/digest")
async def cron_digest(request: Request, background: BackgroundTasks):
    # Cron endpoints must ack 2xx immediately; enqueue/background the actual work.
    return await accept_cron(request, background, "digest", send_digest)


@app.post(P + "/admin/test-digest")
def test_digest(request: Request, user: dict = Depends(require_admin)):
    if not smtp_configured():
        msg = {"email_error": "Email is not set up yet (SMTP details missing)."}
    else:
        try:
            send_email(build_digest(user, digest_context(public_url(request))))
            msg = {"notice": f"This week's digest was sent to {user['email']}."}
        except Exception as exc:
            log.exception("Test digest failed")
            msg = {"email_error": f"Sending failed: {exc}"}
    return RedirectResponse(f"{P}/admin?{urlencode(msg)}#email", status_code=303)
