"""Reads and writes the feature_flags table, plus the env master kill-switch.

Two controls on purpose, and they are not redundant:

  * the DB row is the BUSINESS control — a button Product/Admin can throw
    from the admin surface, no deploy;
  * `GENERAL_CHAT_MASTER_ENABLED` is the ENGINEERING control — if it is off,
    the capability is off whatever the portal says.

Master wins. That ordering is the point: a kill-switch that a database row
can override is not a kill-switch.

Everything here fails CLOSED. A missing row, an unreadable row, a database
that cannot be reached — all answer "disabled". An outage must not be able to
switch a capability ON, and nobody is harmed by general chat being briefly
unavailable, whereas silently enabling it during a DB wobble is exactly the
surprise a feature flag exists to prevent.
"""

import logging
import os

from sqlalchemy.orm import Session

from models.feature_flag import FeatureFlag

logger = logging.getLogger(__name__)

#: The one feature this table currently carries.
GENERAL_CHAT = "general_chat"

#: Every feature the admin surface may read or write. Anything else is a typo
#: (or a probe) and must not create a row that nothing will ever read.
KNOWN_FEATURES = frozenset({GENERAL_CHAT})

GLOBAL_SCOPE = "global"
COMPANY_SCOPE = "company"


def _master_enabled(feature: str) -> bool:
    """The env kill-switch, read PER CALL rather than at import.

    Deliberately not a module-level constant like QUERY_CACHE_ENABLED: those
    are fixed at process start, so flipping one needs a restart. A kill-switch
    that needs a restart is not much of a switch.
    """
    var = f"{feature.upper()}_MASTER_ENABLED"
    return os.getenv(var, "true").strip().lower() not in ("false", "0", "no", "off")


def is_enabled(db: Session, feature: str = GENERAL_CHAT,
               company_id: int | None = None) -> bool:
    """True only when the master switch is on AND a row says so.

    `company_id` is the TENANT (true_company_id), not the per-user company_id
    column used elsewhere in this codebase. A company row wins over the
    global row; with no company row the global one decides; with neither,
    the answer is False.
    """
    if not _master_enabled(feature):
        return False

    try:
        # Ordered so that, should duplicate rows ever exist, the answer is
        # still deterministic (the oldest row wins) rather than row order.
        rows = (
            db.query(FeatureFlag)
            .filter(FeatureFlag.feature == feature)
            .order_by(FeatureFlag.id)
            .all()
        )
    except Exception as e:
        # Fail closed — see the module docstring.
        logger.warning("Feature-flag read failed for %r (treating as disabled): %s",
                       feature, e)
        return False

    if company_id is not None:
        for row in rows:
            if row.scope_type == COMPANY_SCOPE and row.scope_id == company_id:
                return bool(row.enabled)

    for row in rows:
        if row.scope_type == GLOBAL_SCOPE:
            return bool(row.enabled)

    return False


def set_enabled(db: Session, feature: str, enabled: bool, *,
                company_id: int | None = None,
                updated_by: int | None = None) -> FeatureFlag:
    """Creates or updates the one row for this (feature, scope).

    Returns the row so the caller can report what it now says rather than
    echoing back what it was asked to do — those differ when a write lands
    on an existing row.
    """
    scope_type = COMPANY_SCOPE if company_id is not None else GLOBAL_SCOPE

    # .first(), not .one_or_none(): the unique constraint does not stop two
    # GLOBAL rows on its own (Postgres treats the NULL scope_ids as distinct;
    # migration b8c9d0e1f2a3 adds the partial index that does), and
    # one_or_none() on a duplicate raised and turned the toggle into a 500.
    # The oldest row is the one is_enabled() reads, so it is the one written.
    row = (
        db.query(FeatureFlag)
        .filter(
            FeatureFlag.feature == feature,
            FeatureFlag.scope_type == scope_type,
            FeatureFlag.scope_id.is_(None) if company_id is None
            else FeatureFlag.scope_id == company_id,
        )
        .order_by(FeatureFlag.id)
        .first()
    )

    if row is None:
        row = FeatureFlag(
            feature=feature, scope_type=scope_type, scope_id=company_id,
            enabled=enabled, updated_by=updated_by,
        )
        db.add(row)
    else:
        row.enabled = enabled
        row.updated_by = updated_by

    db.commit()
    db.refresh(row)
    return row


def describe(db: Session, feature: str = GENERAL_CHAT) -> dict:
    """What the admin surface shows: every scope row, plus the master switch
    and the effective global answer.

    `master_enabled` is reported separately because a row can read
    enabled=True while the capability is off — without surfacing the master,
    that looks like a bug rather than a deliberate engineering override.
    """
    try:
        rows = (db.query(FeatureFlag).filter(FeatureFlag.feature == feature)
                .order_by(FeatureFlag.id).all())
    except Exception as e:
        logger.warning("Feature-flag listing failed for %r: %s", feature, e)
        rows = []

    return {
        "feature": feature,
        "master_enabled": _master_enabled(feature),
        "effective_global": is_enabled(db, feature),
        "scopes": [
            {
                "scope_type": r.scope_type,
                "scope_id": r.scope_id,
                "enabled": bool(r.enabled),
                "updated_by": r.updated_by,
                "updated_at": r.updated_at.isoformat() if r.updated_at else None,
            }
            for r in rows
        ],
    }
