"""
Minimal HTTP gateway to start the team_created workflow without exposing gRPC to callers.
Run with: uvicorn temporal.gateway:app --host 0.0.0.0 --port 8008
"""
import logging
import os
from typing import Optional

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from temporalio.client import Client

from .types import TeamCreatedInput
from .workflows import TeamCreatedWorkflow

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

app = FastAPI(title="Temporal Gateway", version="0.1.0")


class TeamCreatedRequest(BaseModel):
    team_id: str = Field(..., description="UUID of the team")
    team_name: str
    owner_id: str
    logto_org_id: Optional[str] = ""


async def get_client() -> Client:
    target = os.environ.get("TEMPORAL_ADDRESS", "localhost:7233")
    namespace = os.environ.get("TEMPORAL_NAMESPACE", "default")
    return await Client.connect(target, namespace=namespace)


@app.post("/workflow/team-created")
async def start_team_created(req: TeamCreatedRequest):
    """
    Starts the TeamCreatedWorkflow and returns Temporal identifiers.
    """
    try:
        client = await get_client()
        task_queue = os.environ.get("TEMPORAL_TASK_QUEUE", "teams-team-created")
        handle = await client.start_workflow(
            TeamCreatedWorkflow.run,
            TeamCreatedInput(
                team_id=req.team_id,
                team_name=req.team_name,
                owner_id=req.owner_id,
                logto_org_id=req.logto_org_id or "",
            ),
            id=req.team_id,
            task_queue=task_queue,
        )
        return {"workflow_id": handle.id, "run_id": handle.run_id}
    except Exception as exc:
        logger.exception("Failed to start team-created workflow")
        raise HTTPException(status_code=500, detail=str(exc))
