"""Keycloak SSO deployment playbook.

Defines the steps required to:
1. Set up Keycloak on a tenant server (ENV_UPDATE + DOCKER_RELOAD)
2. Perform initial setup via Playwright automation (create admin, configure realm)

Tenant servers must have stacks and env templates under /opt/letsbe.
"""

import uuid
from typing import Any
from urllib.parse import urlparse

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
KEYCLOAK_ENV_PATH = "/opt/letsbe/env/keycloak.env"
KEYCLOAK_STACK_DIR = "/opt/letsbe/stacks/keycloak"


def build_keycloak_setup_steps(
    *,
    domain: str,
    admin_user: str = "admin",
    admin_password: str,
) -> list[CompositeStep]:
    """
    Build the sequence of steps required to set up Keycloak.

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

    Args:
        domain: The domain for Keycloak (e.g., "auth.example.com")
        admin_user: Admin username (default: "admin")
        admin_password: Admin password

    Returns:
        List of 2 CompositeStep objects:
        1. ENV_UPDATE - patches KC_HOSTNAME, KEYCLOAK_ADMIN, KEYCLOAK_ADMIN_PASSWORD
        2. DOCKER_RELOAD - restarts the keycloak stack with pull=True
    """
    steps = [
        # Step 1: Update environment variables
        CompositeStep(
            type="ENV_UPDATE",
            payload={
                "path": KEYCLOAK_ENV_PATH,
                "updates": {
                    "KC_HOSTNAME": domain,
                    "KEYCLOAK_ADMIN": admin_user,
                    "KEYCLOAK_ADMIN_PASSWORD": admin_password,
                },
            },
        ),
        # Step 2: Reload Docker stack
        CompositeStep(
            type="DOCKER_RELOAD",
            payload={
                "compose_dir": KEYCLOAK_STACK_DIR,
                "pull": True,
            },
        ),
    ]
    return steps


async def create_keycloak_setup_task(
    *,
    db: AsyncSession,
    tenant_id: uuid.UUID,
    agent_id: uuid.UUID | None,
    domain: str,
    admin_user: str = "admin",
    admin_password: str,
) -> Task:
    """
    Create and persist a COMPOSITE task for Keycloak 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 Keycloak
        admin_user: Admin username
        admin_password: Admin password

    Returns:
        The created Task object with type="COMPOSITE"
    """
    steps = build_keycloak_setup_steps(
        domain=domain,
        admin_user=admin_user,
        admin_password=admin_password,
    )

    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_keycloak_initial_setup_step(
    *,
    base_url: str,
    admin_user: str,
    admin_password: str,
    realm_name: str = "letsbe",
) -> dict[str, Any]:
    """
    Build a PLAYWRIGHT task payload for Keycloak initial setup.

    This creates the admin account and configures the "letsbe" realm
    on a fresh Keycloak installation.

    Args:
        base_url: The base URL for Keycloak (e.g., "https://auth.example.com")
        admin_user: Username for the admin account
        admin_password: Password for the admin account
        realm_name: Name of the realm to create (default: "letsbe")

    Returns:
        Task payload dict with type="PLAYWRIGHT"
    """
    parsed = urlparse(base_url)
    allowed_domain = parsed.netloc

    return {
        "scenario": "keycloak_initial_setup",
        "inputs": {
            "base_url": base_url,
            "admin_user": admin_user,
            "admin_password": admin_password,
            "realm_name": realm_name,
        },
        "options": {
            "allowed_domains": [allowed_domain],
        },
        "timeout": 120,
    }


async def create_keycloak_initial_setup_task(
    *,
    db: AsyncSession,
    tenant_id: uuid.UUID,
    agent_id: uuid.UUID,
    base_url: str,
    admin_user: str,
    admin_password: str,
    realm_name: str = "letsbe",
) -> Task:
    """
    Create and persist a PLAYWRIGHT task for Keycloak 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 Keycloak
        admin_user: Username for the admin account
        admin_password: Password for the admin account
        realm_name: Name of the realm to create

    Returns:
        The created Task object with type="PLAYWRIGHT"
    """
    payload = build_keycloak_initial_setup_step(
        base_url=base_url,
        admin_user=admin_user,
        admin_password=admin_password,
        realm_name=realm_name,
    )

    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
