"""
Activity service routes for Memos-style backend.
"""

from typing import List
import re

from fastapi import APIRouter, Depends, HTTPException

from common.memos_core.schemas import ActivityResponse
from common.memos_core.services import get_activity_service


router = APIRouter(prefix="/activities")


@router.get("", summary="List activities", response_model=List[ActivityResponse])
async def list_activities(activity_service=Depends(get_activity_service)):
    try:
        return await activity_service.list_activities()
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=500, detail=str(exc)) from exc


@router.get("/{name:path}", summary="Get activity by name", response_model=ActivityResponse)
async def get_activity(name: str, activity_service=Depends(get_activity_service)):
    """
    Get a single activity by name.
    Name format: activities/{id} or just the ID number.
    """
    try:
        # Extract activity ID from name (e.g., "activities/123456" -> 123456)
        if name.startswith("activities/"):
            name = name[len("activities/"):]
        
        # Parse ID
        match = re.match(r"^(\d+)$", name)
        if not match:
            raise HTTPException(status_code=400, detail=f"Invalid activity name format: {name}")
        
        activity_id = int(match.group(1))
        activity = await activity_service.get_activity(activity_id)
        
        if not activity:
            raise HTTPException(status_code=404, detail=f"Activity {activity_id} not found")
        
        return activity
    except HTTPException:
        raise
    except Exception as exc:  # pragma: no cover
        raise HTTPException(status_code=500, detail=str(exc)) from exc
