# src/dattos_cli/commands/datasets.py
from __future__ import annotations

from typing import Optional

import typer

from dattos_cli.client import ApiError
from dattos_cli.main import get_client, handle_api_error
from dattos_cli.output import print_json

app = typer.Typer(help="Query dataset rows.", no_args_is_help=True)


@app.command("search")
def search_rows(
    analysis_id: int = typer.Argument(help="Analysis ID"),
    load_id: int = typer.Argument(help="Analysis load ID"),
    dataset_id: int = typer.Argument(help="Dataset ID"),
    page_size: int = typer.Option(50, "--page-size", help="Results per page"),
    page: int = typer.Option(0, "--page", help="Page number (0-indexed)"),
    filter_expression: Optional[str] = typer.Option(None, "--filter", "-f", help="Filter expression (JSON string)"),
    folder_id: Optional[str] = typer.Option(None, "--folder-id", help="Folder ID to scope the query"),
):
    """Search rows in a dataset."""
    client = get_client(folder_id)
    body: dict = {
        "offsetInfo": {"page": page, "pageSize": page_size},
    }
    if filter_expression:
        import json as _json
        try:
            body["filter"] = _json.loads(filter_expression)
        except _json.JSONDecodeError:
            from dattos_cli.output import print_error
            print_error("invalid_filter", "Filter must be valid JSON", 1)
            raise typer.Exit(1)
    try:
        result = client.post(
            f"/api/Analysis/{analysis_id}/load/{load_id}/{dataset_id}/SearchRows",
            json=body,
        )
        print_json(result)
    except ApiError as e:
        handle_api_error(e)
