"""
Training Jobs API - ATOMIC CRUD operations
Handles basic training job creation and retrieval
"""

from fastapi import APIRouter, Depends, HTTPException, status, Path, Query, Request
from typing import List, Optional
import structlog
from shared.routing import RouteBuilder
from shared.monitoring.decorators import track_execution_time
from shared.monitoring.metrics import get_metrics_collector
from datetime import datetime
import uuid

from app.services.training_service import EnhancedTrainingService
from app.schemas.training import TrainingJobResponse
from shared.database.base import create_database_manager
from app.core.config import settings

logger = structlog.get_logger()
route_builder = RouteBuilder('training')

router = APIRouter(tags=["training-jobs"])

def get_enhanced_training_service():
    """Dependency injection for EnhancedTrainingService"""
    database_manager = create_database_manager(settings.DATABASE_URL, "training-service")
    return EnhancedTrainingService(database_manager)


@router.get(
    route_builder.build_nested_resource_route("jobs", "job_id", "status")
)
@track_execution_time("enhanced_job_status_duration_seconds", "training-service")
async def get_training_job_status(
    tenant_id: str = Path(..., description="Tenant ID"),
    job_id: str = Path(..., description="Job ID"),
    request_obj: Request = None,
    enhanced_training_service: EnhancedTrainingService = Depends(get_enhanced_training_service)
):
    """
    Get training job status using repository pattern.
    """
    metrics = get_metrics_collector(request_obj)

    try:
        # Get status using enhanced service
        status_info = await enhanced_training_service.get_training_status(job_id)

        if not status_info or status_info.get("error"):
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Training job not found"
            )

        if metrics:
            metrics.increment_counter("enhanced_status_requests_total")

        return {
            **status_info,
            "enhanced_features": True,
            "repository_integration": True
        }

    except HTTPException:
        raise
    except Exception as e:
        if metrics:
            metrics.increment_counter("enhanced_status_errors_total")
        logger.error("Failed to get training status",
                    job_id=job_id,
                    error=str(e))
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get training status"
        )


@router.get(
    route_builder.build_base_route("statistics")
)
@track_execution_time("enhanced_tenant_statistics_duration_seconds", "training-service")
async def get_tenant_statistics(
    tenant_id: str = Path(..., description="Tenant ID"),
    request_obj: Request = None,
    enhanced_training_service: EnhancedTrainingService = Depends(get_enhanced_training_service)
):
    """
    Get comprehensive tenant statistics using repository pattern.
    """
    metrics = get_metrics_collector(request_obj)

    try:
        # Get statistics using enhanced service
        statistics = await enhanced_training_service.get_tenant_statistics(tenant_id)

        if statistics.get("error"):
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=statistics["error"]
            )

        if metrics:
            metrics.increment_counter("enhanced_statistics_requests_total")

        return {
            **statistics,
            "enhanced_features": True,
            "repository_integration": True
        }

    except HTTPException:
        raise
    except Exception as e:
        if metrics:
            metrics.increment_counter("enhanced_statistics_errors_total")
        logger.error("Failed to get tenant statistics",
                    tenant_id=tenant_id,
                    error=str(e))
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to get tenant statistics"
        )
