import uuid

import redis as redis_lib
from fastapi import APIRouter, Depends, HTTPException, status
from geoalchemy2 import Geography
from sqlalchemy import cast, func
from sqlalchemy.orm import Session

from app.api.v1.deps import get_current_user, require_role
from app.db.redis import get_redis
from app.db.session import get_db
from app.models.branch import Branch, BranchApprovalStatus
from app.models.merchant import Merchant
from app.models.user import User, UserRole
from app.schemas.branch import BranchCreateRequest, BranchOut
from app.schemas.merchant import (
    MerchantCreateRequest,
    MerchantOut,
    MerchantUpdateRequest,
)
from app.services.branch_hours import is_branch_open
from app.services.cache import cache_delete, cache_get, cache_set
from app.services.favorites import get_favorited_branch_ids
from app.services.reviews import get_branch_rating_stats


def _branch_out(
    db: Session,
    branch,
    rating_stats: dict[uuid.UUID, tuple[float | None, int]] | None = None,
    customer_id: uuid.UUID | None = None,
    favorited_ids: set[uuid.UUID] | None = None,
) -> BranchOut:
    """Attaches is_open_now fresh, every call — never read from cache,
    since it's time-dependent (see app.services.branch_hours). Also
    attaches average_rating/review_count — pass a pre-fetched
    rating_stats (see app.services.reviews.get_branch_rating_stats)
    when rendering a list of branches, so it's one grouped query for
    the whole list rather than one query per branch; omit it for a
    single-branch response, which just fetches its own.

    is_favorited follows the same bulk-vs-self-fetch split: pass
    customer_id (current_user.id, or None for a non-customer caller —
    see app.services.favorites.get_favorited_branch_ids) and, for a
    list, a pre-fetched favorited_ids set."""
    out = BranchOut.model_validate(branch)
    out.is_open_now = is_branch_open(out)
    if rating_stats is None:
        rating_stats = get_branch_rating_stats(db, [out.id])
    out.average_rating, out.review_count = rating_stats.get(out.id, (None, 0))
    if favorited_ids is None:
        favorited_ids = get_favorited_branch_ids(db, customer_id, [out.id])
    out.is_favorited = out.id in favorited_ids
    return out


router = APIRouter(prefix="/merchants", tags=["merchants"])

_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPERADMIN.value}
_NOT_FOUND = HTTPException(
    status_code=status.HTTP_404_NOT_FOUND, detail="Merchant not found."
)

# Cache keys for the "public" (approved + active) views — safe to
# share across every caller who'd see the exact same thing anyway, per
# the caching eligibility checks at each call site below.


def _public_merchants_key() -> str:
    return "cache:merchants:public"


def _merchant_key(merchant_id: uuid.UUID) -> str:
    return f"cache:merchant:{merchant_id}"


def _public_branches_key(merchant_id: uuid.UUID) -> str:
    return f"cache:branches:{merchant_id}:public"


# One key for "no business_type filter", plus one per actual value —
# only 3 keys total regardless of how many merchants/branches exist,
# unlike a free-text search or lat/lng sort (see
# app.api.v1.endpoints.branches.list_all_branches), so unconditionally
# clearing all 3 on every invalidation is cheap and simple; not worth
# tracking which merchant's business_type to clear just the one.
_ALL_BRANCHES_BUSINESS_TYPES: tuple[str | None, ...] = (None, "restaurant", "grocery")


def _public_all_branches_key(business_type: str | None) -> str:
    return f"cache:branches:all:public:{business_type or 'any'}"


def invalidate_public_caches(redis: redis_lib.Redis, merchant_id: uuid.UUID) -> None:
    """Call this whenever a branch's approval_status or is_active
    changes — the only thing that moves a merchant/branch in or out
    of the public cached views. Used from app.api.v1.endpoints.branches
    (approve_branch)."""
    cache_delete(
        redis,
        _public_merchants_key(),
        _public_branches_key(merchant_id),
        *(_public_all_branches_key(bt) for bt in _ALL_BRANCHES_BUSINESS_TYPES),
    )


def _distance_expr(lat: float, lng: float):
    """Distance in meters between each branch and (lat, lng), computed
    by PostGIS at query time rather than a stored geography column —
    see app.models.branch for why. geoalchemy2.Geography is used only
    as a cast target here, never mapped onto a table column, so it has
    no effect on the SQLite schema the test suite runs against.
    Requires the postgis extension in Postgres; SQLite has no
    equivalent, which is why distance sorting is verified with a live
    smoke test rather than the pytest suite."""
    branch_point = func.ST_SetSRID(
        func.ST_MakePoint(Branch.longitude, Branch.latitude), 4326
    )
    origin_point = func.ST_SetSRID(func.ST_MakePoint(lng, lat), 4326)
    return func.ST_Distance(
        cast(branch_point, Geography), cast(origin_point, Geography)
    ).label("distance_meters")


def _require_merchant_manager(merchant: Merchant, current_user: User) -> None:
    """Admins/superadmins manage any merchant; a supplier can only
    manage merchants they own."""
    if current_user.role in _ADMIN_ROLES:
        return
    if merchant.owner_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You don't own this merchant.",
        )


def _get_merchant_or_404(db: Session, merchant_id: uuid.UUID) -> Merchant:
    merchant = (
        db.query(Merchant)
        .filter(Merchant.id == merchant_id, Merchant.deleted_at.is_(None))
        .first()
    )
    if merchant is None:
        raise _NOT_FOUND
    return merchant


@router.post("", response_model=MerchantOut)
def create_merchant(
    payload: MerchantCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(
        require_role(UserRole.SUPPLIER, UserRole.ADMIN, UserRole.SUPERADMIN)
    ),
) -> MerchantOut:
    """A supplier creates a merchant brand for themselves (a supplier
    may own more than one). An admin can instead create one on behalf
    of a supplier by passing owner_id."""
    if current_user.role in _ADMIN_ROLES:
        if payload.owner_id is None:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
                detail="owner_id is required when an admin creates a merchant.",
            )
        owner = db.get(User, payload.owner_id)
        if owner is None or owner.role != UserRole.SUPPLIER.value:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="No supplier account found for that owner_id.",
            )
        owner_id = owner.id
    else:
        owner_id = current_user.id

    merchant = Merchant(
        owner_id=owner_id,
        name=payload.name,
        description=payload.description,
        logo_url=payload.logo_url,
        business_type=payload.business_type,
    )
    db.add(merchant)
    db.commit()
    db.refresh(merchant)
    return MerchantOut.model_validate(merchant)


@router.get("", response_model=list[MerchantOut])
def list_merchants(
    business_type: str | None = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> list[MerchantOut]:
    """Other users only see a merchant once it has at least one
    visible (approved + active) branch; owners always see their own,
    admins see everything.

    Pass business_type ("restaurant" or "grocery") to show just one —
    the Flutter app's "Restaurants" and "Grocery" tabs. Applied after
    the cache lookup, not as part of the cache key, since the
    underlying cached list already has everything cheaply filterable
    in-memory — no need for a second cache entry per type.

    Only cached for customers: they can never own a merchant, so the
    cached "public" list (merchants with a visible branch) is always
    exactly what they'd get from an uncached query. Suppliers/admins
    always hit the DB directly, since their view is personalized."""
    use_cache = current_user.role == UserRole.CUSTOMER.value
    if use_cache:
        cached = cache_get(redis, _public_merchants_key())
        if cached is not None:
            merchants = [MerchantOut.model_validate(r) for r in cached]
            if business_type is not None:
                merchants = [m for m in merchants if m.business_type == business_type]
            return merchants

    query = db.query(Merchant).filter(Merchant.deleted_at.is_(None))
    if current_user.role not in _ADMIN_ROLES:
        visible_branch_merchant_ids = db.query(Branch.merchant_id).filter(
            Branch.approval_status == BranchApprovalStatus.APPROVED.value,
            Branch.is_active.is_(True),
            Branch.deleted_at.is_(None),
        )
        query = query.filter(
            (Merchant.owner_id == current_user.id)
            | (Merchant.id.in_(visible_branch_merchant_ids))
        )
    merchants = [
        MerchantOut.model_validate(r)
        for r in query.order_by(Merchant.created_at.desc()).all()
    ]

    if use_cache:
        cache_set(
            redis,
            _public_merchants_key(),
            [r.model_dump(mode="json") for r in merchants],
        )

    if business_type is not None:
        merchants = [m for m in merchants if m.business_type == business_type]
    return merchants


@router.get("/{merchant_id}", response_model=MerchantOut)
def get_merchant(
    merchant_id: uuid.UUID,
    db: Session = Depends(get_db),
    _current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MerchantOut:
    """No visibility filtering on a single merchant lookup (see
    _get_merchant_or_404) — every caller who can see it at all sees
    the same thing, so this is always safe to cache."""
    key = _merchant_key(merchant_id)
    cached = cache_get(redis, key)
    if cached is not None:
        return MerchantOut.model_validate(cached)

    merchant_out = MerchantOut.model_validate(_get_merchant_or_404(db, merchant_id))
    cache_set(redis, key, merchant_out.model_dump(mode="json"))
    return merchant_out


@router.patch("/{merchant_id}", response_model=MerchantOut)
def update_merchant(
    merchant_id: uuid.UUID,
    payload: MerchantUpdateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> MerchantOut:
    """Partial — only fields actually sent are changed."""
    merchant = _get_merchant_or_404(db, merchant_id)
    _require_merchant_manager(merchant, current_user)

    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(merchant, field, value)
    db.commit()
    db.refresh(merchant)

    cache_delete(redis, _merchant_key(merchant.id))
    invalidate_public_caches(redis, merchant.id)
    return MerchantOut.model_validate(merchant)


@router.post("/{merchant_id}/branches", response_model=BranchOut)
def create_branch(
    merchant_id: uuid.UUID,
    payload: BranchCreateRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> BranchOut:
    merchant = _get_merchant_or_404(db, merchant_id)
    _require_merchant_manager(merchant, current_user)

    branch = Branch(merchant_id=merchant.id, **payload.model_dump())
    db.add(branch)
    db.commit()
    db.refresh(branch)
    return _branch_out(db, branch)


@router.get("/{merchant_id}/branches", response_model=list[BranchOut])
def list_branches(
    merchant_id: uuid.UUID,
    lat: float | None = None,
    lng: float | None = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> list[BranchOut]:
    """Branches for one merchant. Pass lat & lng to sort by distance
    (nearest first) — customers tap a merchant and see its branches
    this way. Omit them for an unsorted list.

    Cached only for the plain (no lat/lng) list, and only when the
    caller isn't the owner or an admin — a distance sort is
    caller-specific by nature (a different origin point every time)
    and not worth caching, and the owner/admin view includes
    unapproved branches the public cache must never contain."""
    merchant = _get_merchant_or_404(db, merchant_id)
    is_admin = current_user.role in _ADMIN_ROLES
    is_owner = merchant.owner_id == current_user.id
    use_cache = not is_admin and not is_owner and lat is None and lng is None
    customer_id = (
        current_user.id if current_user.role == UserRole.CUSTOMER.value else None
    )

    if use_cache:
        cached = cache_get(redis, _public_branches_key(merchant.id))
        if cached is not None:
            ids = [uuid.UUID(b["id"]) for b in cached]
            stats = get_branch_rating_stats(db, ids)
            favorited = get_favorited_branch_ids(db, customer_id, ids)
            return [_branch_out(db, b, stats, customer_id, favorited) for b in cached]

    query = db.query(Branch).filter(
        Branch.merchant_id == merchant.id, Branch.deleted_at.is_(None)
    )
    if not (is_admin or is_owner):
        query = query.filter(
            Branch.approval_status == BranchApprovalStatus.APPROVED.value,
            Branch.is_active.is_(True),
        )

    if lat is not None and lng is not None:
        distance = _distance_expr(lat, lng)
        rows = query.add_columns(distance).order_by(distance).all()
        ids = [branch.id for branch, _d in rows]
        stats = get_branch_rating_stats(db, ids)
        favorited = get_favorited_branch_ids(db, customer_id, ids)
        results = []
        for branch, distance_meters in rows:
            out = _branch_out(db, branch, stats, customer_id, favorited)
            out.distance_meters = distance_meters
            results.append(out)
        return results

    branch_rows = query.order_by(Branch.created_at.desc()).all()
    ids = [b.id for b in branch_rows]
    stats = get_branch_rating_stats(db, ids)
    favorited = get_favorited_branch_ids(db, customer_id, ids)
    branches = [_branch_out(db, b, stats, customer_id, favorited) for b in branch_rows]
    if use_cache:
        cache_set(
            redis,
            _public_branches_key(merchant.id),
            [b.model_dump(mode="json") for b in branches],
        )
    return branches
