"""Bulk operation commands — batch-start analyses, batch-create users."""
from __future__ import annotations

import json
from pathlib import Path

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, validate_date

app = typer.Typer(help="Bulk operations.", no_args_is_help=True)


def _batch_operation(items, operation_fn, label: str) -> dict:
    """Run operation_fn on each item, collect results."""
    succeeded = []
    failed = []
    for item in items:
        try:
            result = operation_fn(item)
            succeeded.append(result)
        except ApiError as e:
            failed.append({"item": item, "error": e.detail})
    return {"succeeded": succeeded, "failed": failed, "total": len(items)}


@app.command("batch-start")
def batch_start(
    ids: str = typer.Option(..., "--ids", help="Comma-separated analysis IDs."),
    date: str = typer.Option(..., "--date", "-d", help="Reference date (YYYY-MM-DD)."),
    folder_id: str = typer.Option(None, "--folder-id", help="Folder ID to scope the query."),
):
    """Start execution for multiple analyses sequentially."""
    validate_date(date)
    client = get_client(folder_id)

    try:
        analysis_ids = [int(x.strip()) for x in ids.split(",")]
    except ValueError:
        from dattos_cli.output import print_error
        print_error("invalid_input", f"IDs must be comma-separated integers, got: {ids}", 1)
        raise typer.Exit(1)

    def start_one(analysis_id: int) -> dict:
        body = {"ReferenceDate": date, "IncrementalImporting": False, "Files": []}
        client.post(f"/api/Analysis/{analysis_id}/Execution/Start", json=body)
        return {"analysisId": analysis_id, "status": "started"}

    result = _batch_operation(analysis_ids, start_one, "analyses")
    print_json(result)
    if result["failed"]:
        raise typer.Exit(1)


@app.command("batch-create")
def batch_create(
    file: str = typer.Option(..., "--file", help="Path to JSON file with user data."),
):
    """Create multiple users from a JSON file."""
    file_path = Path(file)
    if not file_path.exists():
        from dattos_cli.output import print_error
        print_error("file_not_found", f"File not found: {file}", 1)
        raise typer.Exit(1)

    try:
        users = json.loads(file_path.read_text())
    except (json.JSONDecodeError, OSError) as e:
        from dattos_cli.output import print_error
        print_error("invalid_input", f"Failed to read JSON file: {e}", 1)
        raise typer.Exit(1)

    client = get_client()

    def create_one(user: dict) -> dict:
        payload = {
            "UserCode": user["code"],
            "FullName": user["name"],
            "EmailAddress": user["email"],
            "Culture": user.get("culture", "pt-BR"),
            "Blocked": False,
            "SupportUser": False,
            "Id": 0,
        }
        return client.post("/api/User", json=payload)

    result = _batch_operation(users, create_one, "users")
    print_json(result)
    if result["failed"]:
        raise typer.Exit(1)
