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

from __future__ import annotations

import uuid

from sqlalchemy import select
from sqlalchemy.orm import Session

from legate.agent.enums import RunStatus
from legate.db.models.run import Run


def create(
    db: Session,
    *,
    workspace_id: uuid.UUID,
    agent_id: uuid.UUID | None = None,
    workflow_id: uuid.UUID | None = None,
    input: dict,
    created_by: uuid.UUID | None = None,
) -> Run:
    run = Run(
        workspace_id=workspace_id,
        agent_id=agent_id,
        workflow_id=workflow_id,
        input=input,
        status=RunStatus.PENDING,
        created_by=created_by,
    )
    db.add(run)
    db.flush()
    return run


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


def list_for_workspace(
    db: Session, *, workspace_id: uuid.UUID, limit: int = 100, offset: int = 0
) -> list[Run]:
    return list(
        db.scalars(
            select(Run)
            .where(Run.workspace_id == workspace_id)
            .order_by(Run.created_at.desc())
            .limit(limit)
            .offset(offset)
        ).all()
    )
