import asyncio
import logging
import os
from typing import Tuple

from temporalio.client import Client

from .models import Team

logger = logging.getLogger(__name__)

# Default Temporal connection settings; override via env.
TEMPORAL_ADDRESS = os.getenv("TEMPORAL_ADDRESS", "temporal:7233")
TEMPORAL_NAMESPACE = os.getenv("TEMPORAL_NAMESPACE", "default")
TEMPORAL_TASK_QUEUE = os.getenv("TEMPORAL_TASK_QUEUE", "teams-team-created")


async def _start_team_created_async(team: Team) -> Tuple[str, str]:
    """
    Start the team_created workflow in Temporal and return (workflow_id, run_id).
    """
    client = await Client.connect(TEMPORAL_ADDRESS, namespace=TEMPORAL_NAMESPACE)

    # We re-use team.uuid as workflow_id to keep idempotency.
    handle = await client.start_workflow(
        "team_created_workflow",  # workflow name registered in worker
        {
            "team_id": team.uuid,
            "team_name": team.name,
            "owner_id": getattr(getattr(team.owner, "profile", None), "logto_id", "") or getattr(team.owner, "username", ""),
            "logto_org_id": team.logto_org_id or "",
        },
        id=team.uuid,
        task_queue=TEMPORAL_TASK_QUEUE,
    )
    return handle.id, handle.run_id


def start_team_created(team: Team) -> Tuple[str, str]:
    """
    Sync wrapper for Django mutation handlers.
    """
    try:
        return asyncio.run(_start_team_created_async(team))
    except Exception:
        logger.exception("Failed to start Temporal workflow for team %s", team.uuid)
        raise
