"""Git auto-commit API routes."""

import logging
from typing import Any

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

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 AutoCommitStatus(BaseModel):
    """Auto-commit status response."""

    enabled: bool


class UndoResult(BaseModel):
    """Undo result response."""

    success: bool
    message: str


@router.get("/{session_id}/git/autocommit", response_model=AutoCommitStatus)
async def get_autocommit_status(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> AutoCommitStatus:
    """Get auto-commit 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 AutoCommitStatus(enabled=getattr(session, "auto_commit", False))


@router.post("/{session_id}/git/autocommit", response_model=AutoCommitStatus)
async def toggle_autocommit(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> AutoCommitStatus:
    """Toggle auto-commit 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")
    session.auto_commit = not getattr(session, "auto_commit", False)
    return AutoCommitStatus(enabled=session.auto_commit)


@router.post("/{session_id}/git/undo", response_model=UndoResult)
async def undo_last_commit(
    session_id: str,
    request: Request,
    session_service: Any = Depends(get_session_service),
) -> UndoResult:
    """Undo the last git commit 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")

    try:
        from ieum.git.auto_commit import AutoCommitManager

        mgr = AutoCommitManager(repo_path=session.working_directory)
        result = mgr.undo_last_commit()
        if result.success:
            return UndoResult(success=True, message=result.message)
        return UndoResult(success=False, message=result.error or "Undo failed")
    except Exception as e:
        return UndoResult(success=False, message=str(e))
