"""Card update skills — allow agents to write back enrichment data."""

from __future__ import annotations

from sqlalchemy import and_, or_

from luca_assistant.db.engine import get_session
from luca_assistant.db.models import Card, CardBenefit


def update_card_benefit(
    card_name: str,
    category: str,
    multiplier: float,
    points_type: str,
    notes: str | None = None,
    bank: str | None = None,
    annual_credit: int | None = None,
    credit_category: str | None = None,
) -> dict:
    """Upsert a benefit row for a card. Matches on (card, category)."""
    session = get_session()
    try:
        query = session.query(Card).filter(
            or_(
                Card.name.ilike(f"%{card_name}%"),
                Card.full_name.ilike(f"%{card_name}%"),
            )
        )
        if bank:
            query = query.filter(Card.bank.ilike(f"%{bank}%"))

        card = query.first()
        if not card:
            return {"error": f"No card found matching '{card_name}'"}

        existing = (
            session.query(CardBenefit)
            .filter(and_(CardBenefit.card_id == card.id, CardBenefit.category == category))
            .first()
        )

        if existing:
            existing.multiplier = multiplier
            existing.points_type = points_type
            if notes is not None:
                existing.notes = notes
            if annual_credit is not None:
                existing.annual_credit = annual_credit
            if credit_category is not None:
                existing.credit_category = credit_category
            action = "updated"
        else:
            session.add(
                CardBenefit(
                    card_id=card.id,
                    category=category,
                    multiplier=multiplier,
                    points_type=points_type,
                    annual_credit=annual_credit,
                    credit_category=credit_category,
                    notes=notes,
                )
            )
            action = "created"

        session.commit()
        return {
            "status": "ok",
            "action": action,
            "card": card.full_name,
            "category": category,
            "multiplier": multiplier,
            "points_type": points_type,
        }
    finally:
        session.close()
