"""Owner notices in the platform bell: the Notifications table in the master DB, one row per active owner.

The AI credit pool and the storage allowances are the organisation's, shared by every product, so the product
whose call happens to cross a mark is the one that settles it. Rather than each product carrying its own
notifier, the library writes the notice itself, named GalaxiQ, not a product. A product may still pass its own
`tell_owners` to Credits; this is what runs otherwise.
"""
from __future__ import annotations

import logging
import uuid
from datetime import datetime
from typing import List

log = logging.getLogger("galaxiq.ai_credits")

NOTIFICATION_TYPE = "OTHER"   # the platform's general type; the title says what it is


def owner_notice(mark: int, used: int, limit: int, renews_at: datetime) -> tuple:
    """(title, description) for an AI credit mark, in the owner's words."""
    when = f"on {renews_at.day} {renews_at:%b}" if renews_at else "with your next billing period"
    if mark >= 100:
        return ("GalaxiQ: AI credits used up",
                f"You have used all {limit:,} AI credits for this period. AI work across your GalaxiQ products "
                f"waits until they renew {when}, or sooner with a larger plan or an add-on.")
    return (f"GalaxiQ: {mark}% of your AI credits used",
            f"You have used {used:,} of {limit:,} AI credits for this period. They renew {when}.")


def find_members(conn, tenant_id: str) -> List[str]:
    """User ids of every active member of the organisation, however the product spells the tenant. Everyone in
    the organisation hears about its AI credits and storage, not only the owners (decided 2026-10-31)."""
    rows = conn.execute(
        'SELECT m."userId" FROM "Organisations" o '
        'JOIN "OrganisationMembers" m ON m."organisationId" = o.id '
        'WHERE o."tenantId"::text = %s AND m."userId" IS NOT NULL AND upper(m.status) = %s',
        (str(tenant_id).removeprefix("org_"), "ACTIVE")).fetchall()
    return [str(r[0]) for r in rows]


def tell_members(conn, tenant_id: str, title: str, description: str) -> int:
    """Writes one bell notice for every active member of the organisation; returns how many were told."""
    members = find_members(conn, tenant_id)
    for user_id in members:
        conn.execute(
            'INSERT INTO "Notifications" (id, "userId", title, description, type, "createdAt", "updatedAt") '
            "VALUES (%s, %s, %s, %s, %s, now(), now())",
            (str(uuid.uuid4()), user_id, title, description, NOTIFICATION_TYPE))
    conn.commit()
    if not members:
        log.info("notices: %s has no active member to tell about %r", tenant_id, title)
    return len(members)


def tell_members_in_the_bell(conn, tenant_id: str, mark: int, used: int, limit: int, renews_at: datetime) -> int:
    """The AI credit notice at a mark, for every owner."""
    title, description = owner_notice(mark, used, limit, renews_at)
    return tell_members(conn, tenant_id, title, description)
