"""
Centralized query filters for ResolutionFlow.

Provides reusable SQLAlchemy filter builders for tree access control,
step visibility, and the canonical tenant_filter used by all queries
on tenant-scoped tables.
"""
from __future__ import annotations
import uuid
from typing import TYPE_CHECKING

from sqlalchemy import or_, and_, true as sa_true

if TYPE_CHECKING:
    from app.models.user import User


def tenant_filter(model, account_id: uuid.UUID):
    """Primary app-layer tenant filter.

    MUST be used in every SELECT/UPDATE/DELETE on tenant tables.
    RLS (Phase 2) is the safety net — this is the primary enforcement.

    Usage:
        stmt = select(Tree).where(tenant_filter(Tree, current_user.account_id), ...)
    """
    return model.account_id == account_id


def build_tree_access_filter(current_user: User):
    """Build the access filter for trees based on user permissions.

    Visibility rules:
    - super_admin: sees everything
    - is_default: visible to all authenticated users
    - visibility='public': visible to all authenticated users
    - author_id == me: always visible (regardless of visibility setting)
    - visibility='team' AND account_id == mine: visible to account members
    - visibility='private': only visible to author (covered by author_id check above)
    - visibility='link': only visible to author (share token access is handled separately)
    """
    from app.models.tree import Tree

    if current_user.is_super_admin:
        return sa_true()

    conditions = [
        Tree.is_default == True,
        Tree.visibility == 'public',
        Tree.author_id == current_user.id,
    ]
    if current_user.account_id:
        # Team-visible trees: use tenant_filter as the account match
        conditions.append(
            and_(
                Tree.visibility == 'team',
                tenant_filter(Tree, current_user.account_id),
            )
        )
    return or_(*conditions)


def build_step_visibility_filter(current_user: User):
    """Build SQLAlchemy filter for step visibility based on user.

    Returns steps that are:
    - Public steps (visible to all)
    - Team steps (visible to same account members)
    - User's own private steps
    """
    from app.models.step_library import StepLibrary

    if current_user.account_id:
        return or_(
            StepLibrary.visibility == 'public',
            and_(
                StepLibrary.visibility == 'team',
                tenant_filter(StepLibrary, current_user.account_id),
            ),
            StepLibrary.created_by == current_user.id,
        )
    else:
        return or_(
            StepLibrary.visibility == 'public',
            StepLibrary.created_by == current_user.id,
        )
