"""
Mail API — task (Arbeitsvorrat) endpoints.
"""

import logging
from datetime import datetime
from typing import Optional, List

from fastapi import APIRouter, HTTPException, Query

from .models import (
    TaskCreate,
    TaskUpdate,
    TaskDashboardStats,
    TaskStatus,
    TaskPriority,
)
from .mail_db import get_email
from .task_service import get_task_service

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/v1/mail", tags=["Mail"])


@router.get("/tasks", response_model=List[dict])
async def list_tasks(
    user_id: str = Query(..., description="User ID"),
    status: Optional[str] = Query(None, description="Filter by status"),
    priority: Optional[str] = Query(None, description="Filter by priority"),
    include_completed: bool = Query(False),
    limit: int = Query(50, ge=1, le=200),
    offset: int = Query(0, ge=0),
):
    """Get all tasks for a user."""
    task_service = get_task_service()

    status_enum = TaskStatus(status) if status else None
    priority_enum = TaskPriority(priority) if priority else None

    tasks = await task_service.get_user_tasks(
        user_id=user_id,
        status=status_enum,
        priority=priority_enum,
        include_completed=include_completed,
        limit=limit,
        offset=offset,
    )

    return tasks


@router.post("/tasks", response_model=dict)
async def create_task(
    request: TaskCreate,
    user_id: str = Query(..., description="User ID"),
    tenant_id: str = Query(..., description="Tenant ID"),
):
    """Create a new task manually."""
    task_service = get_task_service()

    task_id = await task_service.create_manual_task(
        user_id=user_id,
        tenant_id=tenant_id,
        task_data=request,
    )

    if not task_id:
        raise HTTPException(status_code=500, detail="Failed to create task")

    return {"id": task_id, "status": "created"}


@router.get("/tasks/dashboard", response_model=TaskDashboardStats)
async def get_task_dashboard(
    user_id: str = Query(..., description="User ID"),
):
    """Get dashboard statistics for tasks."""
    task_service = get_task_service()
    return await task_service.get_dashboard_stats(user_id)


@router.get("/tasks/{task_id}", response_model=dict)
async def get_task(
    task_id: str,
    user_id: str = Query(..., description="User ID"),
):
    """Get a single task."""
    task_service = get_task_service()
    task = await task_service.get_task(task_id, user_id)

    if not task:
        raise HTTPException(status_code=404, detail="Task not found")

    return task


@router.put("/tasks/{task_id}")
async def update_task(
    task_id: str,
    request: TaskUpdate,
    user_id: str = Query(..., description="User ID"),
):
    """Update a task."""
    task_service = get_task_service()

    success = await task_service.update_task(task_id, user_id, request)
    if not success:
        raise HTTPException(status_code=500, detail="Failed to update task")

    return {"status": "updated"}


@router.post("/tasks/{task_id}/complete")
async def complete_task(
    task_id: str,
    user_id: str = Query(..., description="User ID"),
):
    """Mark a task as completed."""
    task_service = get_task_service()

    success = await task_service.mark_completed(task_id, user_id)
    if not success:
        raise HTTPException(status_code=500, detail="Failed to complete task")

    return {"status": "completed"}


@router.post("/tasks/from-email/{email_id}")
async def create_task_from_email(
    email_id: str,
    user_id: str = Query(..., description="User ID"),
    tenant_id: str = Query(..., description="Tenant ID"),
):
    """Create a task from an email (after analysis)."""
    email_data = await get_email(email_id, user_id)
    if not email_data:
        raise HTTPException(status_code=404, detail="Email not found")

    # Get deadlines from stored analysis
    deadlines_raw = email_data.get("detected_deadlines", [])
    from .models import DeadlineExtraction, SenderType

    deadlines = []
    for d in deadlines_raw:
        try:
            deadlines.append(DeadlineExtraction(
                deadline_date=datetime.fromisoformat(d["date"]),
                description=d.get("description", "Frist"),
                confidence=0.8,
                source_text="",
                is_firm=d.get("is_firm", True),
            ))
        except (KeyError, ValueError):
            continue

    sender_type = None
    if email_data.get("sender_type"):
        try:
            sender_type = SenderType(email_data["sender_type"])
        except ValueError:
            pass

    task_service = get_task_service()
    task_id = await task_service.create_task_from_email(
        user_id=user_id,
        tenant_id=tenant_id,
        email_id=email_id,
        deadlines=deadlines,
        sender_type=sender_type,
    )

    if not task_id:
        raise HTTPException(status_code=500, detail="Failed to create task")

    return {"id": task_id, "status": "created"}
