"""Groups commands — CRUD for groups plus person/contact membership management."""

from __future__ import annotations

import json

import typer

from turumba_cli.client import TurumbaClient
from turumba_cli.config import get_value
from turumba_cli.errors import TurumbaAPIError, TurumbaAuthError
from turumba_cli.output import error, render, render_meta, success

app = typer.Typer(name="groups", help="Manage groups and their person/contact membership.")

API_PATH = "/v1/groups"

LIST_COLUMNS = {
    "ID": "id",
    "Name": "name",
    "Description": "description",
    "Persons": "persons_count",
    "Contacts": "contacts_count",
    "Created At": "created_at",
}


def _handle_error(e: Exception) -> None:
    if isinstance(e, TurumbaAuthError | TurumbaAPIError):
        error(str(e))
    else:
        error(f"Unexpected error: {e}")
    raise typer.Exit(1)


@app.command("list")
def list_groups(
    filter_: list[str] | None = typer.Option(None, "--filter", "-f", help="Filter: field:op:value"),
    sort: list[str] | None = typer.Option(None, "--sort", "-s", help="Sort: field:asc|desc"),
    limit: int = typer.Option(100, "--limit", "-l", help="Max results"),
    skip: int = typer.Option(0, "--skip", help="Offset"),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json, csv"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """List groups."""
    client = TurumbaClient(gateway_url=gateway_url)
    try:
        data, meta = client.list(API_PATH, filter_=filter_, sort=sort, limit=limit, skip=skip)
    except Exception as e:
        _handle_error(e)

    render(data, output_format=output, columns=LIST_COLUMNS, title="Groups")
    render_meta(meta, output_format=output)


@app.command("get")
def get_group(
    group_id: str = typer.Argument(help="Group ID"),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Get details of a specific group."""
    client = TurumbaClient(gateway_url=gateway_url)
    try:
        data = client.get(API_PATH, group_id)
    except Exception as e:
        _handle_error(e)

    render(data, output_format=output, is_list=False, title="Group Details")


@app.command("create")
def create_group(
    name: str = typer.Option(..., "--name", "-n", help="Group name"),
    description: str = typer.Option(None, "--description", "-d", help="Group description"),
    account_id: str = typer.Option(
        None, "--account-id", "-a", help="Account ID (defaults to config default_account_id)"
    ),
    metadata: str = typer.Option(None, "--metadata", "-m", help="Metadata as JSON string"),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Create a new group."""
    resolved_account_id = account_id or get_value("default_account_id")
    if not resolved_account_id:
        error(
            "account_id is required. Use --account-id or set: turumba config set default_account_id <id>"
        )
        raise typer.Exit(1)

    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {"account_id": resolved_account_id, "name": name}
    if description:
        data["description"] = description
    if metadata:
        data["metadata"] = json.loads(metadata)

    try:
        result = client.create(API_PATH, data)
    except Exception as e:
        _handle_error(e)

    success(f"Group created: {result.get('id', '')}")
    render(result, output_format=output, is_list=False, title="Created Group")


@app.command("update")
def update_group(
    group_id: str = typer.Argument(help="Group ID"),
    name: str = typer.Option(None, "--name", "-n", help="Group name"),
    description: str = typer.Option(None, "--description", "-d", help="Group description"),
    metadata: str = typer.Option(None, "--metadata", "-m", help="Metadata as JSON string"),
    replace_metadata: bool = typer.Option(
        False, "--replace-metadata", help="Replace all metadata instead of merging"
    ),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Update an existing group."""
    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {}
    if name:
        data["name"] = name
    if description:
        data["description"] = description
    if metadata:
        data["metadata"] = json.loads(metadata)
    if replace_metadata:
        data["replace_metadata"] = True

    if not data:
        error("No fields to update. Provide at least one option.")
        raise typer.Exit(1)

    try:
        result = client.update(API_PATH, group_id, data, method="PUT")
    except Exception as e:
        _handle_error(e)

    success(f"Group updated: {group_id}")
    render(result, output_format=output, is_list=False, title="Updated Group")


@app.command("delete")
def delete_group(
    group_id: str = typer.Argument(help="Group ID"),
    force: bool = typer.Option(False, "--force", "-y", help="Skip confirmation"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Delete a group (also removes all person/contact memberships)."""
    if not force:
        typer.confirm(f"Delete group {group_id}?", abort=True)

    client = TurumbaClient(gateway_url=gateway_url)
    try:
        client.delete(API_PATH, group_id)
    except Exception as e:
        _handle_error(e)

    success(f"Group deleted: {group_id}")


# ── Person membership sub-commands ──────────────────────────────────────────


@app.command("add-persons")
def add_persons(
    group_id: str = typer.Argument(help="Group ID"),
    person_ids: list[str] = typer.Option(..., "--person-id", "-p", help="Person ID(s) to add"),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Add existing persons to a group."""
    client = TurumbaClient(gateway_url=gateway_url)
    try:
        result = client.post(f"{API_PATH}/{group_id}/persons", {"person_ids": person_ids})
    except Exception as e:
        _handle_error(e)

    data = result.get("data", result) if isinstance(result, dict) else result
    success(
        f"Added: {data.get('added', 0)}, "
        f"Created: {data.get('created', 0)}, "
        f"Skipped: {data.get('skipped', 0)}"
    )
    render(data, output_format=output, is_list=False, title="Add Persons Result")


@app.command("list-persons")
def list_persons(
    group_id: str = typer.Argument(help="Group ID"),
    limit: int = typer.Option(100, "--limit", "-l", help="Max results"),
    skip: int = typer.Option(0, "--skip", help="Offset"),
    output: str = typer.Option("table", "--output", "-o", help="Output format: table, json, csv"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """List persons in a group."""
    client = TurumbaClient(gateway_url=gateway_url)
    try:
        data, meta = client.list(f"{API_PATH}/{group_id}/persons", limit=limit, skip=skip)
    except Exception as e:
        _handle_error(e)

    person_columns = {
        "ID": "id",
        "Properties": "properties",
        "Created At": "created_at",
    }
    render(data, output_format=output, columns=person_columns, title="Group Persons")
    render_meta(meta, output_format=output)


@app.command("remove-persons")
def remove_persons(
    group_id: str = typer.Argument(help="Group ID"),
    person_ids: list[str] = typer.Option(..., "--person-id", "-p", help="Person ID(s) to remove"),
    force: bool = typer.Option(False, "--force", "-y", help="Skip confirmation"),
    gateway_url: str = typer.Option(None, "--gateway-url", "-g", help="Gateway URL override"),
) -> None:
    """Remove persons from a group."""
    if not force:
        typer.confirm(f"Remove {len(person_ids)} person(s) from group {group_id}?", abort=True)

    client = TurumbaClient(gateway_url=gateway_url)
    try:
        result = client.request(
            "DELETE", f"{API_PATH}/{group_id}/persons", json_data={"person_ids": person_ids}
        )
    except Exception as e:
        _handle_error(e)

    data = result.get("data", result) if isinstance(result, dict) else result
    success(f"Removed: {data.get('removed', 0)}, Not found: {data.get('not_found', 0)}")
