"""Two-week invoice upload reminder job."""

from __future__ import annotations

import logging
from datetime import date, datetime, timedelta

from sqlalchemy import select

from app.db import SessionLocal, UploadReminderRow
from app.store import store

logger = logging.getLogger(__name__)

REMINDER_TYPE = "invoice_upload"
PERIOD_DAYS = 14


def _period_bounds(today: date | None = None) -> tuple[str, str]:
    today = today or date.today()
    end = today
    start = today - timedelta(days=PERIOD_DAYS)
    return start.isoformat(), end.isoformat()


def _latest_upload_date(client_id: str) -> str | None:
    dates = [
        inv.uploadedAt
        for inv in store.snapshot().invoices
        if inv.clientId == client_id and inv.uploadedAt
    ]
    if not dates:
        return None
    return max(dates)


def run_upload_reminders(*, dry_run: bool = False) -> dict[str, int]:
    """
    For each client, check whether new documents were uploaded in the current
    two-week period compared to the previous period. Send at most one reminder
    per client per period.
    """
    period_start, period_end = _period_bounds()
    prev_start = (date.fromisoformat(period_start) - timedelta(days=PERIOD_DAYS)).isoformat()
    prev_end = period_start

    sent = 0
    skipped = 0
    checked = 0

    for client in store.snapshot().clients:
        checked += 1
        last_doc = _latest_upload_date(client.id)

        with SessionLocal() as session:
            existing = session.scalar(
                select(UploadReminderRow).where(
                    UploadReminderRow.client_id == client.id,
                    UploadReminderRow.period_start == period_start,
                    UploadReminderRow.period_end == period_end,
                )
            )
            if existing:
                skipped += 1
                continue

        # No uploads ever → remind
        # Latest upload before current period start → no new uploads this period
        needs_reminder = False
        if not last_doc:
            needs_reminder = True
        elif last_doc < period_start:
            needs_reminder = True

        if not needs_reminder:
            skipped += 1
            continue

        if dry_run:
            sent += 1
            continue

        now = datetime.utcnow()
        try:
            with SessionLocal() as session:
                row = UploadReminderRow(
                    client_id=client.id,
                    reminder_type=REMINDER_TYPE,
                    period_start=period_start,
                    period_end=period_end,
                    last_document_at=last_doc,
                    previous_document_at=prev_end,
                    reminder_sent_at=now,
                    status="sent",
                    created_at=now,
                )
                session.add(row)
                session.commit()

            from app.services import notifications as notif

            notif.on_upload_reminder(client_id=client.id, client_name=client.name)
            store._log(  # noqa: SLF001
                "reminder",
                f"Invoice upload reminder sent to {client.name}",
                "Amanah",
                client.id,
            )
            sent += 1
        except Exception:
            logger.exception("Failed to send upload reminder for client %s", client.id)

    return {"checked": checked, "sent": sent, "skipped": skipped, "periodStart": period_start, "periodEnd": period_end}
