"""
Unified Inbox Mail API — barrel re-export.

The actual endpoints live in:
  - api_accounts.py (account CRUD, test, sync)
  - api_inbox.py    (unified inbox, email detail, send)
  - api_ai.py       (AI analysis, response suggestions)
  - api_tasks.py    (task CRUD, dashboard, from-email)
"""

import logging

from fastapi import APIRouter, HTTPException, Query

from .models import MailHealthCheck, MailStats
from .mail_db import init_mail_tables, get_mail_stats

from .api_accounts import router as _accounts_router
from .api_inbox import router as _inbox_router
from .api_ai import router as _ai_router
from .api_tasks import router as _tasks_router

logger = logging.getLogger(__name__)

router = APIRouter()

# Merge sub-routers
router.include_router(_accounts_router)
router.include_router(_inbox_router)
router.include_router(_ai_router)
router.include_router(_tasks_router)


# =============================================================================
# Health & Init (kept here as they are small)
# =============================================================================

@router.get("/api/v1/mail/health", response_model=MailHealthCheck)
async def health_check():
    """Health check for the mail system."""
    return MailHealthCheck(
        status="healthy",
        database_connected=True,
        vault_connected=True,
    )


@router.post("/api/v1/mail/init")
async def initialize_mail_system():
    """Initialize mail database tables."""
    success = await init_mail_tables()
    if not success:
        raise HTTPException(status_code=500, detail="Failed to initialize mail tables")
    return {"status": "initialized"}


# =============================================================================
# Statistics
# =============================================================================

@router.get("/api/v1/mail/stats", response_model=MailStats)
async def get_statistics(
    user_id: str = Query(..., description="User ID"),
):
    """Get overall mail statistics for a user."""
    stats = await get_mail_stats(user_id)
    return MailStats(**stats)
