"""Teams commands — CRUD for teams plus member 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="teams", help="Manage teams and team membership.")

API_PATH = "/v1/teams"

LIST_COLUMNS = {
    "ID": "id",
    "Name": "name",
    "Account ID": "account_id",
    "Lead ID": "lead_id",
    "Active": "is_active",
    "Created At": "created_at",
}

MEMBER_COLUMNS = {
    "ID": "id",
    "User ID": "user_id",
    "Role": "role",
    "Active": "is_active",
    "Email": "user.email",
    "Given Name": "user.given_name",
    "Family Name": "user.family_name",
}


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


def _resolve_account_id(account_id: str | None) -> str:
    resolved = account_id or get_value("default_account_id")
    if not resolved:
        error(
            "account_id is required. Use --account-id or set: "
            "turumba config set default_account_id <id>"
        )
        raise typer.Exit(1)
    return resolved


@app.command("list")
def list_teams(
    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 teams."""
    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="Teams")
    render_meta(meta, output_format=output)


@app.command("get")
def get_team(
    team_id: str = typer.Argument(help="Team 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 team."""
    client = TurumbaClient(gateway_url=gateway_url)
    try:
        data = client.get(API_PATH, team_id)
    except Exception as e:
        _handle_error(e)

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


@app.command("create")
def create_team(
    name: str = typer.Option(..., "--name", "-n", help="Team name"),
    account_id: str = typer.Option(
        None, "--account-id", "-a", help="Account ID (defaults to config default_account_id)"
    ),
    description: str = typer.Option(None, "--description", "-d", help="Team description"),
    lead_id: str = typer.Option(None, "--lead-id", help="User ID of team lead"),
    is_active: bool = typer.Option(True, "--active/--inactive", help="Team active status"),
    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 team."""
    resolved_account_id = _resolve_account_id(account_id)
    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {"name": name, "account_id": resolved_account_id}
    if description is not None:
        data["description"] = description
    if lead_id is not None:
        data["lead_id"] = lead_id
    if not is_active:
        data["is_active"] = False
    if metadata is not None:
        data["metadata"] = json.loads(metadata)

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

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


@app.command("update")
def update_team(
    team_id: str = typer.Argument(help="Team ID"),
    name: str = typer.Option(None, "--name", "-n", help="Team name"),
    description: str = typer.Option(None, "--description", "-d", help="Team description"),
    lead_id: str = typer.Option(None, "--lead-id", help="User ID of team lead"),
    is_active: bool | None = typer.Option(None, "--active/--inactive", help="Team active status"),
    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:
    """Update an existing team."""
    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {}
    if name is not None:
        data["name"] = name
    if description is not None:
        data["description"] = description
    if lead_id is not None:
        data["lead_id"] = lead_id
    if is_active is not None:
        data["is_active"] = is_active
    if metadata is not None:
        data["metadata"] = json.loads(metadata)

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

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

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


@app.command("delete")
def delete_team(
    team_id: str = typer.Argument(help="Team 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 team."""
    if not force:
        typer.confirm(f"Delete team {team_id}?", abort=True)

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

    success(f"Team deleted: {team_id}")


# ── Team Members ─────────────────────────────────────────────────────────────


@app.command("list-members")
def list_members(
    team_id: str = typer.Argument(help="Team 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 members of a team."""
    client = TurumbaClient(gateway_url=gateway_url)
    try:
        data, meta = client.list(f"{API_PATH}/{team_id}/members", limit=limit, skip=skip)
    except Exception as e:
        _handle_error(e)

    render(data, output_format=output, columns=MEMBER_COLUMNS, title="Team Members")
    render_meta(meta, output_format=output)


@app.command("add-members")
def add_members(
    team_id: str = typer.Argument(help="Team ID"),
    user_ids: list[str] = typer.Option(..., "--user-id", "-u", help="User ID(s) to add"),
    role: str = typer.Option("member", "--role", "-r", help="Role: member or lead"),
    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 members to a team."""
    client = TurumbaClient(gateway_url=gateway_url)

    data = {"user_ids": user_ids, "role": role}

    try:
        result = client.create(f"{API_PATH}/{team_id}/members", data)
    except Exception as e:
        _handle_error(e)

    added = result.get("added", 0)
    skipped = result.get("skipped", 0)
    success(f"Added {added} member(s), skipped {skipped}")
    render(result, output_format=output, is_list=False, title="Add Members Result")


@app.command("remove-members")
def remove_members(
    team_id: str = typer.Argument(help="Team ID"),
    user_ids: list[str] = typer.Option(..., "--user-id", "-u", help="User ID(s) to remove"),
    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:
    """Remove members from a team."""
    client = TurumbaClient(gateway_url=gateway_url)

    data = {"user_ids": user_ids}

    try:
        result = client.request("POST", f"{API_PATH}/{team_id}/members/remove", json=data)
    except Exception as e:
        _handle_error(e)

    removed = result.get("removed", 0)
    not_found = result.get("not_found", 0)
    success(f"Removed {removed} member(s), {not_found} not found")
    render(result, output_format=output, is_list=False, title="Remove Members Result")
