/**
 * Metadata Enrichment Service Routes
 * API endpoints for controlling the metadata enrichment service
 */ import { Router } from "express";
import { getMetadataEnrichmentService } from "./metadataEnrichmentService.js";
import { serverLogger } from "../utils/serverLogger.js";
// Authentication is handled in routes.ts with checkAuth
export function createMetadataEnrichmentRoutes() {
    const router = Router();
    // Get current configuration and status
    router.get("/config", (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            const config = service.getConfig();
            const stats = service.getStats();
            res.json({
                config,
                stats
            });
        } catch (error) {
            serverLogger.error("Failed to get enrichment config:", error);
            res.status(500).json({
                error: "Failed to get configuration"
            });
        }
    });
    // Update configuration
    router.post("/config", (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            const newConfig = req.body;
            // Validate config structure
            if (typeof newConfig !== "object") {
                return res.status(400).json({
                    error: "Invalid configuration"
                });
            }
            service.updateConfig(newConfig);
            res.json({
                success: true,
                config: service.getConfig()
            });
        } catch (error) {
            serverLogger.error("Failed to update enrichment config:", error);
            res.status(500).json({
                error: "Failed to update configuration"
            });
        }
    });
    // Start the enrichment service
    router.post("/start", (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            service.updateConfig({
                enabled: true
            });
            res.json({
                success: true,
                message: "Metadata enrichment service started"
            });
        } catch (error) {
            serverLogger.error("Failed to start enrichment service:", error);
            res.status(500).json({
                error: "Failed to start service"
            });
        }
    });
    // Stop the enrichment service
    router.post("/stop", (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            service.updateConfig({
                enabled: false
            });
            res.json({
                success: true,
                message: "Metadata enrichment service stopped"
            });
        } catch (error) {
            serverLogger.error("Failed to stop enrichment service:", error);
            res.status(500).json({
                error: "Failed to stop service"
            });
        }
    });
    // Trigger the NON-DESTRUCTIVE MBID fill-only backfill.
    //
    // Raises MusicBrainz-ID coverage WITHOUT renaming artist/album/title (unlike
    // fill-holes / pool-full). Runs in the BACKGROUND — responds immediately with
    // { status: "started" }; progress is surfaced via GET /progress.
    //
    // Body/query params:
    //   useAcoustID (boolean, default false) — also run the slow fingerprint pass
    //   max (number, default unlimited)      — cap tracks scanned per phase
    //
    // NOTE: must be registered BEFORE /trigger/:task so it isn't swallowed by it.
    router.post("/trigger/mbid-fill", (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            const rawUseAcoustID = req.body?.useAcoustID ?? req.query?.useAcoustID;
            const useAcoustID = rawUseAcoustID === true || rawUseAcoustID === "true" || rawUseAcoustID === "1";
            const rawMax = req.body?.max ?? req.query?.max;
            const parsedMax = rawMax !== undefined ? parseInt(String(rawMax), 10) : NaN;
            const maxTracks = Number.isFinite(parsedMax) && parsedMax > 0 ? parsedMax : undefined;
            // Fire-and-forget: do NOT await — let it run in the background.
            service.fillMbidsOnly({
                useAcoustID,
                maxTracks
            }).then((result)=>{
                serverLogger.info("[MBID-FILL] Backfill finished", result);
            }).catch((error)=>{
                serverLogger.error("[MBID-FILL] Backfill failed:", error);
            });
            res.json({
                status: "started",
                task: "mbid-fill",
                useAcoustID,
                maxTracks: maxTracks ?? null,
                message: "Non-destructive MBID fill-only backfill started (see /progress)"
            });
        } catch (error) {
            serverLogger.error("Failed to start MBID fill-only backfill:", error);
            res.status(500).json({
                error: "Failed to start MBID fill-only backfill"
            });
        }
    });
    // Manually trigger specific tasks
    router.post("/trigger/:task", async (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            const { task } = req.params;
            let taskName = "";
            switch(task){
                case "fill-holes":
                    await service.runTask("fillHoles");
                    taskName = "Fill metadata holes";
                    break;
                case "verify":
                    await service.runTask("verifyMetadata");
                    taskName = "Verify metadata";
                    break;
                case "enrich":
                    await service.runTask("enrichFromAPIs");
                    taskName = "Enrich from APIs";
                    break;
                case "test":
                    await service.runTask("test");
                    taskName = "Test progress";
                    break;
                case "fix-all":
                    await service.runTask("fixAll");
                    taskName = "Fix entire library";
                    break;
                case "fetch-artwork":
                    await service.runTask("fetchArtwork");
                    taskName = "Fetch missing artwork";
                    break;
                case "fetch-artist-images":
                    await service.runTask("fetchArtistImages");
                    taskName = "Fetch artist images";
                    break;
                case "cleanup-invalid-artists":
                    await service.runTask("cleanupInvalidArtists");
                    taskName = "Cleanup invalid artists";
                    break;
                case "pool-full":
                    await service.runTask("enrichAllFromPool");
                    taskName = "Full library POOL sync";
                    break;
                default:
                    return res.status(400).json({
                        error: `Invalid task: ${task}`
                    });
            }
            res.json({
                success: true,
                message: `${taskName} task triggered`
            });
        } catch (error) {
            serverLogger.error(`Failed to trigger task ${req.params.task}:`, error);
            res.status(500).json({
                error: "Failed to trigger task"
            });
        }
    });
    // Get service status
    router.get("/status", (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            const config = service.getConfig();
            const stats = service.getStats();
            res.json({
                isRunning: stats.isRunning,
                schedulingEnabled: config.enabled,
                tasks: config.tasks,
                schedule: config.schedule,
                lastRun: stats.lastRun,
                nextScheduledRun: stats.nextScheduledRun,
                runningTasks: stats.runningTasks,
                stats: {
                    artworkFetched: stats.artworkFetched,
                    artistImagesFetched: stats.artistImagesFetched,
                    metadataUpdated: stats.metadataUpdated
                }
            });
        } catch (error) {
            serverLogger.error("Failed to get enrichment status:", error);
            res.status(500).json({
                error: "Failed to get status"
            });
        }
    });
    // Get enrichment statistics
    router.get("/stats", (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            const stats = service.getStats();
            res.json(stats);
        } catch (error) {
            serverLogger.error("Failed to get enrichment stats:", error);
            res.status(500).json({
                error: "Failed to get statistics"
            });
        }
    });
    // Get current progress
    router.get("/progress", (req, res)=>{
        try {
            const service = getMetadataEnrichmentService();
            const stats = service.getStats();
            // Log progress for debugging
            if (stats.currentProgress) {
                serverLogger.debug("Sending progress to client:", stats.currentProgress);
            }
            res.json({
                isRunning: stats.runningTasks && stats.runningTasks.length > 0,
                runningTasks: stats.runningTasks,
                currentProgress: stats.currentProgress,
                stats: {
                    artworkFetched: stats.artworkFetched,
                    artistImagesFetched: stats.artistImagesFetched,
                    metadataUpdated: stats.metadataUpdated,
                    lastRun: stats.lastRun
                }
            });
        } catch (error) {
            serverLogger.error("Failed to get enrichment progress:", error);
            res.status(500).json({
                error: "Failed to get progress"
            });
        }
    });
    return router;
}

//# sourceMappingURL=metadataEnrichmentRoutes.js.map