"""Cross-pit search functionality."""

from typing import Any

from pydantic import BaseModel

from mosh.metadata import StoredObject
from mosh.pit import Pit


def search_pits(pits: list[Pit], **criteria: Any) -> list[StoredObject[BaseModel]]:
    """Search across multiple pits.

    Args:
        pits: List of pits to search.
        **criteria: Field-value pairs to match.

    Returns:
        List of matching StoredObjects from all pits.
    """
    results: list[StoredObject[BaseModel]] = []
    for pit in pits:
        results.extend(pit.search_stored(**criteria))
    return results


def search_pits_objects(pits: list[Pit], **criteria: Any) -> list[BaseModel]:
    """Search across multiple pits (convenience method).

    Returns just the objects without metadata wrapper.
    """
    return [stored.obj for stored in search_pits(pits, **criteria)]


def search_by_type(pits: list[Pit], obj_type: type[BaseModel]) -> list[StoredObject[BaseModel]]:
    """Find all objects of a specific type across pits.

    Args:
        pits: List of pits to search.
        obj_type: The BaseModel subclass to find.

    Returns:
        List of StoredObjects matching the specified type.
    """
    type_name = obj_type.__name__
    results: list[StoredObject[BaseModel]] = []
    for pit in pits:
        results.extend(pit.search_stored(type_name=type_name))
    return results


def search_by_type_objects(pits: list[Pit], obj_type: type[BaseModel]) -> list[BaseModel]:
    """Find all objects of a specific type across pits (convenience method).

    Returns just the objects without metadata wrapper.
    """
    return [stored.obj for stored in search_by_type(pits, obj_type)]


def search_tags_across_pits(pits: list[Pit], tags: list[str], match_all: bool = False) -> list[StoredObject[BaseModel]]:
    """Search for objects with specific tags across multiple pits.

    Args:
        pits: List of pits to search.
        tags: Tags to search for.
        match_all: If True, object must have all tags. If False, any tag matches.

    Returns:
        List of matching StoredObjects from all pits.
    """
    results: list[StoredObject[BaseModel]] = []
    for pit in pits:
        results.extend(pit.search_tags_stored(tags, match_all=match_all))
    return results


def search_tags_across_pits_objects(pits: list[Pit], tags: list[str], match_all: bool = False) -> list[BaseModel]:
    """Search for objects with specific tags across pits (convenience method).

    Returns just the objects without metadata wrapper.
    """
    return [stored.obj for stored in search_tags_across_pits(pits, tags, match_all)]
