"""Messages commands — CRUD for individual messages."""

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="messages", help="Manage individual messages (outbound, inbound, system).")

API_PATH = "/v1/messages"

LIST_COLUMNS = {
    "ID": "id",
    "Direction": "direction",
    "Status": "status",
    "Delivery Address": "delivery_address",
    "Body": "message_body",
    "Channel ID": "channel_id",
    "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)


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_messages(
    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 messages."""
    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="Messages")
    render_meta(meta, output_format=output)


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

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


@app.command("create")
def create_message(
    message_body: str = typer.Option(..., "--body", "-b", help="Message body text"),
    direction: str = typer.Option(
        "outbound", "--direction", "-d", help="Direction: outbound, inbound, system"
    ),
    account_id: str = typer.Option(
        None, "--account-id", "-a", help="Account ID (defaults to config default_account_id)"
    ),
    channel_id: str = typer.Option(None, "--channel-id", "-c", help="Delivery channel ID"),
    delivery_address: str = typer.Option(
        None, "--delivery-address", help="Recipient address (phone, chat ID, email, etc.)"
    ),
    contact_id: str = typer.Option(None, "--contact-id", help="Contact ID"),
    template_id: str = typer.Option(None, "--template-id", help="Template ID used to render body"),
    scheduled_at: str = typer.Option(None, "--scheduled-at", help="ISO 8601 datetime to send at"),
    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 message."""
    resolved_account_id = _resolve_account_id(account_id)
    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {
        "account_id": resolved_account_id,
        "direction": direction,
        "message_body": message_body,
    }
    if channel_id is not None:
        data["channel_id"] = channel_id
    if delivery_address is not None:
        data["delivery_address"] = delivery_address
    if contact_id is not None:
        data["contact_id"] = contact_id
    if template_id is not None:
        data["template_id"] = template_id
    if scheduled_at is not None:
        data["scheduled_at"] = scheduled_at
    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"Message created: {result.get('id', '')} ({direction})")
    render(result, output_format=output, is_list=False, title="Created Message")


@app.command("update")
def update_message(
    message_id: str = typer.Argument(help="Message ID"),
    status: str = typer.Option(
        None,
        "--status",
        help="Status: queued, sending, sent, delivered, failed, permanently_failed, scheduled",
    ),
    sent_at: str = typer.Option(None, "--sent-at", help="ISO 8601 datetime when sent"),
    delivered_at: str = typer.Option(
        None, "--delivered-at", help="ISO 8601 datetime when delivered"
    ),
    failed_at: str = typer.Option(None, "--failed-at", help="ISO 8601 datetime when failed"),
    error_details: str = typer.Option(None, "--error-details", help="Error details as JSON string"),
    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 message."""
    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {}
    if status is not None:
        data["status"] = status
    if sent_at is not None:
        data["sent_at"] = sent_at
    if delivered_at is not None:
        data["delivered_at"] = delivered_at
    if failed_at is not None:
        data["failed_at"] = failed_at
    if error_details is not None:
        data["error_details"] = json.loads(error_details)
    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, message_id, data)
    except Exception as e:
        _handle_error(e)

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


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

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

    success(f"Message deleted: {message_id}")
