"""Training Export Endpoints."""

import logging
from datetime import datetime

from fastapi import APIRouter, HTTPException

from backend.web.core.auth import AdminTokenDep, DocumentRepoDep, AnnotationRepoDep
from backend.web.schemas.admin import (
    ExportRequest,
    ExportResponse,
)
from backend.web.schemas.common import ErrorResponse

logger = logging.getLogger(__name__)


def register_export_routes(router: APIRouter) -> None:
    """Register export endpoints on the router."""

    @router.post(
        "/export",
        response_model=ExportResponse,
        responses={
            400: {"model": ErrorResponse, "description": "Invalid request"},
            401: {"model": ErrorResponse, "description": "Invalid token"},
        },
        summary="Export annotations",
        description="Export annotations in YOLO format for training.",
    )
    async def export_annotations(
        request: ExportRequest,
        admin_token: AdminTokenDep,
        docs: DocumentRepoDep,
        annotations: AnnotationRepoDep,
    ) -> ExportResponse:
        """Export annotations for training."""
        from backend.web.services.storage_helpers import get_storage_helper

        # Get storage helper for reading images and exports directory
        storage = get_storage_helper()

        if request.format not in ("yolo", "coco", "voc"):
            raise HTTPException(
                status_code=400,
                detail=f"Unsupported export format: {request.format}",
            )

        documents = docs.get_labeled_for_export(admin_token)

        if not documents:
            raise HTTPException(
                status_code=400,
                detail="No labeled documents available for export",
            )

        # Get exports directory from StorageHelper
        exports_base = storage.get_exports_base_path()
        if exports_base is None:
            raise HTTPException(
                status_code=500,
                detail="Storage not configured for local access",
            )
        export_dir = exports_base / f"export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}"
        export_dir.mkdir(parents=True, exist_ok=True)

        (export_dir / "images" / "train").mkdir(parents=True, exist_ok=True)
        (export_dir / "images" / "val").mkdir(parents=True, exist_ok=True)
        (export_dir / "labels" / "train").mkdir(parents=True, exist_ok=True)
        (export_dir / "labels" / "val").mkdir(parents=True, exist_ok=True)

        total_docs = len(documents)
        train_count = int(total_docs * request.split_ratio)
        train_docs = documents[:train_count]
        val_docs = documents[train_count:]

        total_images = 0
        total_annotations = 0

        for split, docs in [("train", train_docs), ("val", val_docs)]:
            for doc in docs:
                doc_annotations = annotations.get_for_document(str(doc.document_id))

                if not doc_annotations:
                    continue

                for page_num in range(1, doc.page_count + 1):
                    page_annotations = [a for a in doc_annotations if a.page_number == page_num]

                    if not page_annotations and not request.include_images:
                        continue

                    # Get image from storage
                    doc_id = str(doc.document_id)
                    if not storage.admin_image_exists(doc_id, page_num):
                        continue

                    # Download image and save to export directory
                    image_name = f"{doc.document_id}_page{page_num}.png"
                    dst_image = export_dir / "images" / split / image_name
                    image_content = storage.get_admin_image(doc_id, page_num)
                    dst_image.write_bytes(image_content)
                    total_images += 1

                    label_name = f"{doc.document_id}_page{page_num}.txt"
                    label_path = export_dir / "labels" / split / label_name

                    with open(label_path, "w") as f:
                        for ann in page_annotations:
                            line = f"{ann.class_id} {ann.x_center:.6f} {ann.y_center:.6f} {ann.width:.6f} {ann.height:.6f}\n"
                            f.write(line)
                            total_annotations += 1

        from shared.fields import FIELD_CLASSES

        yaml_content = f"""# Auto-generated YOLO dataset config
path: {export_dir.absolute()}
train: images/train
val: images/val

nc: {len(FIELD_CLASSES)}
names: {list(FIELD_CLASSES.values())}
"""
        (export_dir / "data.yaml").write_text(yaml_content)

        return ExportResponse(
            status="completed",
            export_path=str(export_dir),
            total_images=total_images,
            total_annotations=total_annotations,
            train_count=len(train_docs),
            val_count=len(val_docs),
            message=f"Exported {total_images} images with {total_annotations} annotations",
        )
