"""Core interaction checking logic."""
from itertools import combinations

from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.interaction import Interaction
from app.schemas.interaction import InteractionCheckResponse, InteractionDetail


class InteractionService:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def check(self, item_ids: list[str]) -> InteractionCheckResponse:
        """Check all pairwise interactions for the given item IDs.

        Generates all unique pairs from the input list, then queries the
        interactions table for matches in either direction (a,b) or (b,a).
        """
        pairs = list(combinations(sorted(set(item_ids)), 2))
        if not pairs:
            return InteractionCheckResponse(interactions=[], total_checked=0)

        # Build OR conditions for all pairs
        conditions = []
        for a, b in pairs:
            conditions.append(
                (Interaction.item_a == a) & (Interaction.item_b == b)
            )
            conditions.append(
                (Interaction.item_a == b) & (Interaction.item_b == a)
            )

        result = await self.db.execute(
            select(Interaction).where(or_(*conditions))
        )
        found = result.scalars().all()

        interactions = [
            InteractionDetail(
                item_a=row.item_a,
                item_b=row.item_b,
                severity=row.severity,
                description=row.description,
                mechanism=row.mechanism,
                recommendation=row.recommendation,
                source=row.source,
            )
            for row in found
        ]

        # Sort by severity (critical first)
        severity_order = {"critical": 0, "high": 1, "moderate": 2, "low": 3, "info": 4}
        interactions.sort(key=lambda x: severity_order.get(x.severity, 99))

        return InteractionCheckResponse(
            interactions=interactions,
            total_checked=len(pairs),
        )
