"""Agent repository (tenant-scoped)."""

from __future__ import annotations

import uuid

from sqlalchemy import select
from sqlalchemy.orm import Session

from legate.db.models.agent import Agent


def create(
    db: Session,
    *,
    workspace_id: uuid.UUID,
    name: str,
    description: str = "",
    system_prompt: str = "",
    provider: str = "",
    model: str = "",
    tools: list[str] | None = None,
    memory_config: dict | None = None,
    guardrails_json: dict | None = None,
    created_by: uuid.UUID | None = None,
) -> Agent:
    agent = Agent(
        workspace_id=workspace_id,
        name=name,
        description=description,
        system_prompt=system_prompt,
        provider=provider,
        model=model,
        tools=tools or [],
        memory_config=memory_config or {},
        guardrails_json=guardrails_json or {},
        created_by=created_by,
    )
    db.add(agent)
    db.flush()
    return agent


def get(db: Session, *, workspace_id: uuid.UUID, agent_id: uuid.UUID) -> Agent | None:
    return db.scalars(
        select(Agent).where(Agent.id == agent_id, Agent.workspace_id == workspace_id)
    ).first()


def list_for_workspace(db: Session, *, workspace_id: uuid.UUID) -> list[Agent]:
    return list(
        db.scalars(
            select(Agent).where(Agent.workspace_id == workspace_id).order_by(Agent.created_at.asc())
        ).all()
    )


def delete(db: Session, agent: Agent) -> None:
    db.delete(agent)
    db.flush()
