"""Chat endpoints commands — CRUD for embeddable chat widgets."""

from __future__ import annotations

import json

import typer

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

app = typer.Typer(name="chat-endpoints", help="Manage chat endpoints for embeddable widgets.")

API_PATH = "/v1/chat-endpoints"

LIST_COLUMNS = {
    "ID": "id",
    "Name": "name",
    "Public Key": "public_key",
    "Active": "is_active",
    "Channel": "channel_id",
    "Created": "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_chat_endpoints(
    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 chat endpoints."""
    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="Chat Endpoints")
    render_meta(meta, output_format=output)


@app.command("get")
def get_chat_endpoint(
    endpoint_id: str = typer.Argument(help="Chat endpoint 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 chat endpoint."""
    client = TurumbaClient(gateway_url=gateway_url)
    try:
        data = client.get(API_PATH, endpoint_id)
    except Exception as e:
        _handle_error(e)

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


@app.command("create")
def create_chat_endpoint(
    name: str = typer.Option(..., "--name", "-n", help="Chat endpoint name"),
    description: str = typer.Option(None, "--description", "-d", help="Description"),
    is_active: bool = typer.Option(True, "--active/--inactive", help="Enable or disable endpoint"),
    widget_config: str = typer.Option(None, "--widget-config", help="Widget configuration as JSON"),
    pre_chat_form: str = typer.Option(None, "--pre-chat-form", help="Pre-chat form config as JSON"),
    allowed_origins: list[str] = typer.Option(
        None, "--origin", help="Allowed CORS origins (repeat for multiple)"
    ),
    welcome_message: str = typer.Option(None, "--welcome-message", help="Welcome message text"),
    offline_message: str = typer.Option(None, "--offline-message", help="Offline message text"),
    channel_id: str = typer.Option(None, "--channel-id", help="Associated channel ID"),
    metadata: str = typer.Option(None, "--metadata", help="Custom metadata as JSON"),
    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 chat endpoint."""
    client = TurumbaClient(gateway_url=gateway_url)

    data: dict = {"name": name, "is_active": is_active}
    if description:
        data["description"] = description
    if widget_config:
        data["widget_config"] = json.loads(widget_config)
    if pre_chat_form:
        data["pre_chat_form"] = json.loads(pre_chat_form)
    if allowed_origins:
        data["allowed_origins"] = allowed_origins
    if welcome_message:
        data["welcome_message"] = welcome_message
    if offline_message:
        data["offline_message"] = offline_message
    if channel_id:
        data["channel_id"] = channel_id
    if metadata:
        data["metadata"] = json.loads(metadata)

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

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


@app.command("update")
def update_chat_endpoint(
    endpoint_id: str = typer.Argument(help="Chat endpoint ID"),
    name: str = typer.Option(None, "--name", "-n", help="Endpoint name"),
    description: str = typer.Option(None, "--description", "-d", help="Description"),
    is_active: bool = typer.Option(None, "--active/--inactive", help="Enable or disable endpoint"),
    widget_config: str = typer.Option(None, "--widget-config", help="Widget configuration as JSON"),
    pre_chat_form: str = typer.Option(None, "--pre-chat-form", help="Pre-chat form config as JSON"),
    allowed_origins: str = typer.Option(
        None, "--allowed-origins", help="Allowed CORS origins as JSON array"
    ),
    welcome_message: str = typer.Option(None, "--welcome-message", help="Welcome message text"),
    offline_message: str = typer.Option(None, "--offline-message", help="Offline message text"),
    channel_id: str = typer.Option(None, "--channel-id", help="Associated channel ID"),
    metadata: str = typer.Option(None, "--metadata", help="Custom metadata as JSON"),
    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 chat endpoint."""
    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 is_active is not None:
        data["is_active"] = is_active
    if widget_config is not None:
        data["widget_config"] = json.loads(widget_config)
    if pre_chat_form is not None:
        data["pre_chat_form"] = json.loads(pre_chat_form)
    if allowed_origins is not None:
        data["allowed_origins"] = json.loads(allowed_origins)
    if welcome_message is not None:
        data["welcome_message"] = welcome_message
    if offline_message is not None:
        data["offline_message"] = offline_message
    if channel_id is not None:
        data["channel_id"] = channel_id
    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, endpoint_id, data)
    except Exception as e:
        _handle_error(e)

    success(f"Chat endpoint updated: {endpoint_id}")
    render(result, output_format=output, is_list=False, title="Updated Chat Endpoint")


@app.command("delete")
def delete_chat_endpoint(
    endpoint_id: str = typer.Argument(help="Chat endpoint 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 chat endpoint."""
    if not force:
        typer.confirm(f"Delete chat endpoint {endpoint_id}?", abort=True)

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

    success(f"Chat endpoint deleted: {endpoint_id}")
