"""Chatwoot deployment playbook.

Defines the steps required to set up Chatwoot on a tenant server
that already has stacks and env templates under /opt/letsbe.
"""

import uuid
from typing import Any

from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.task import Task, TaskStatus


class CompositeStep(BaseModel):
    """A single step in a composite playbook."""

    type: str = Field(..., description="Task type (e.g., ENV_UPDATE, DOCKER_RELOAD)")
    payload: dict[str, Any] = Field(
        default_factory=dict, description="Payload for this step"
    )


# LetsBe standard paths
CHATWOOT_ENV_PATH = "/opt/letsbe/env/chatwoot.env"
CHATWOOT_STACK_DIR = "/opt/letsbe/stacks/chatwoot"


def build_chatwoot_setup_steps(*, domain: str) -> list[CompositeStep]:
    """
    Build the sequence of steps required to set up Chatwoot.

    Assumes the env file already exists at /opt/letsbe/env/chatwoot.env
    (created by provisioning/env_setup.sh).

    Args:
        domain: The domain for Chatwoot (e.g., "support.example.com")

    Returns:
        List of 2 CompositeStep objects:
        1. ENV_UPDATE - patches FRONTEND_URL and BACKEND_URL
        2. DOCKER_RELOAD - restarts the chatwoot stack with pull=True
    """
    steps = [
        # Step 1: Update environment variables
        CompositeStep(
            type="ENV_UPDATE",
            payload={
                "path": CHATWOOT_ENV_PATH,
                "updates": {
                    "FRONTEND_URL": f"https://{domain}",
                    "BACKEND_URL": f"https://{domain}",
                },
            },
        ),
        # Step 2: Reload Docker stack
        CompositeStep(
            type="DOCKER_RELOAD",
            payload={
                "compose_dir": CHATWOOT_STACK_DIR,
                "pull": True,
            },
        ),
    ]
    return steps


async def create_chatwoot_setup_task(
    *,
    db: AsyncSession,
    tenant_id: uuid.UUID,
    agent_id: uuid.UUID | None,
    domain: str,
) -> Task:
    """
    Create and persist a COMPOSITE task for Chatwoot setup.

    Args:
        db: Async database session
        tenant_id: UUID of the tenant
        agent_id: Optional UUID of the agent to assign the task to
        domain: The domain for Chatwoot

    Returns:
        The created Task object with type="COMPOSITE"
    """
    steps = build_chatwoot_setup_steps(domain=domain)

    task = Task(
        tenant_id=tenant_id,
        agent_id=agent_id,
        type="COMPOSITE",
        payload={"steps": [step.model_dump() for step in steps]},
        status=TaskStatus.PENDING.value,
    )

    db.add(task)
    await db.commit()
    await db.refresh(task)

    return task


# =============================================================================
# Initial Setup via Playwright
# =============================================================================


def build_chatwoot_initial_setup_step(
    *,
    base_url: str,
    admin_name: str,
    company_name: str,
    admin_email: str,
    admin_password: str | None = None,
) -> dict[str, Any]:
    """
    Build a PLAYWRIGHT task payload for Chatwoot initial setup.

    This creates the super admin account on a fresh Chatwoot installation.

    Args:
        base_url: The base URL for Chatwoot (e.g., "https://chatwoot.example.com")
        admin_name: Full name for the admin account
        company_name: Company/organization name
        admin_email: Email address for the admin account
        admin_password: Password for admin (auto-generated if None)

    Returns:
        Task payload dict with type="PLAYWRIGHT"
    """
    from urllib.parse import urlparse

    # Extract domain from URL for allowlist
    parsed = urlparse(base_url)
    allowed_domain = parsed.netloc

    inputs: dict[str, Any] = {
        "base_url": base_url,
        "admin_name": admin_name,
        "company_name": company_name,
        "admin_email": admin_email,
    }

    # Only include password if provided
    if admin_password:
        inputs["admin_password"] = admin_password

    return {
        "scenario": "chatwoot_initial_setup",
        "inputs": inputs,
        "options": {
            "allowed_domains": [allowed_domain],
        },
        "timeout": 120,
    }


async def create_chatwoot_initial_setup_task(
    *,
    db: AsyncSession,
    tenant_id: uuid.UUID,
    agent_id: uuid.UUID,
    base_url: str,
    admin_name: str,
    company_name: str,
    admin_email: str,
    admin_password: str | None = None,
) -> Task:
    """
    Create and persist a PLAYWRIGHT task for Chatwoot initial setup.

    Args:
        db: Async database session
        tenant_id: UUID of the tenant
        agent_id: UUID of the agent to assign the task to
        base_url: The base URL for Chatwoot
        admin_name: Full name for the admin account
        company_name: Company/organization name
        admin_email: Email address for the admin account
        admin_password: Password for admin (auto-generated if None)

    Returns:
        The created Task object with type="PLAYWRIGHT"
    """
    payload = build_chatwoot_initial_setup_step(
        base_url=base_url,
        admin_name=admin_name,
        company_name=company_name,
        admin_email=admin_email,
        admin_password=admin_password,
    )

    task = Task(
        tenant_id=tenant_id,
        agent_id=agent_id,
        type="PLAYWRIGHT",
        payload=payload,
        status=TaskStatus.PENDING.value,
    )

    db.add(task)
    await db.commit()
    await db.refresh(task)

    return task
