"""Plan mode API routes."""

import logging
from typing import Any

from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field

from ieum.server.auth import get_request_user_id

logger = logging.getLogger(__name__)

router = APIRouter()


def get_session_service(request: Request) -> Any:
    """Dependency to get the session service."""
    return request.app.state.session_service


class PlanModeStatus(BaseModel):
    """Plan mode status response."""

    plan_mode: bool
    approval_policy: str
    current_plan: str | None = None


class PlanModeSet(BaseModel):
    """Request body for setting plan mode."""

    enable: bool = Field(..., description="Enable or disable plan mode")
    task: str | None = Field(default=None, description="Optional task description for planning")


class PlanApproveResult(BaseModel):
    """Result of approving a plan."""

    success: bool
    message: str


@router.get("/{session_id}/plan", response_model=PlanModeStatus)
async def get_plan_status(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> PlanModeStatus:
    """Get plan mode status for a session."""
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    return PlanModeStatus(
        plan_mode=session.plan_mode,
        approval_policy=session.approval_policy,
        current_plan=session.current_plan,
    )


@router.post("/{session_id}/plan/mode", response_model=PlanModeStatus)
async def set_plan_mode(
    session_id: str,
    body: PlanModeSet,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> PlanModeStatus:
    """Enable or disable plan mode for a session."""
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    if body.enable:
        if not session.plan_mode:
            session.enter_plan_mode()
            if body.task:
                session._plan_original_task = body.task
    else:
        if session.plan_mode:
            session.exit_plan_mode()

    return PlanModeStatus(
        plan_mode=session.plan_mode,
        approval_policy=session.approval_policy,
        current_plan=session.current_plan,
    )


@router.post("/{session_id}/plan/approve", response_model=PlanApproveResult)
async def approve_plan(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> PlanApproveResult:
    """Approve the current plan and exit plan mode.

    The approved plan is stored on the session for the next chat message
    to pick up and execute.
    """
    user_id = get_request_user_id(request)
    session = session_service.get_session(session_id, user_id=user_id)
    if session is None:
        raise HTTPException(status_code=404, detail="Session not found")

    if not session.current_plan:
        raise HTTPException(status_code=400, detail="No plan to approve")

    # Exit plan mode (restores approval policy)
    session.exit_plan_mode()

    return PlanApproveResult(
        success=True,
        message="Plan approved. Send a message to execute.",
    )
