"""Contacts commands — CRUD for contact records (MongoDB, dynamic properties)."""

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="contacts", help="Manage contacts (dynamic-property contact records).")

API_PATH = "/v1/contacts"

LIST_COLUMNS = {
    "ID": "id",
    "Account ID": "account_id",
    "Properties": "properties",
    "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_contacts(
    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 contacts."""
    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="Contacts")
    render_meta(meta, output_format=output)


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

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


@app.command("create")
def create_contact(
    account_id: str = typer.Option(
        None, "--account-id", "-a", help="Account ID (defaults to config default_account_id)"
    ),
    properties: str = typer.Option(None, "--properties", "-p", help="Properties 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 contact."""
    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}
    if properties:
        data["properties"] = json.loads(properties)

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

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


@app.command("update")
def update_contact(
    contact_id: str = typer.Argument(help="Contact ID"),
    properties: str = typer.Option(None, "--properties", "-p", help="Properties as JSON string"),
    replace_properties: bool = typer.Option(
        False, "--replace", help="Replace all properties 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 contact."""
    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {}
    if properties:
        data["properties"] = json.loads(properties)
    if replace_properties:
        data["replace_properties"] = True

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

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

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


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

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

    success(f"Contact deleted: {contact_id}")
