/**
 * Artwork API Routes
 * Handles storage and retrieval of artwork URLs from mobile app
 */ import express from "express";
import { getArtworkStorageService } from "./artworkStorageService.js";
import { getArtworkService } from "./artworkService.js";
import { serverLogger } from "../utils/logger.js";
import path from "path";
import fs from "fs";
// sharp is optional - image processing will be disabled if not available
let sharp = null;
(async ()=>{
    try {
        const sharpModule = await import("sharp");
        sharp = sharpModule.default;
    } catch (error) {
        serverLogger.info("Sharp package not available - image processing disabled");
    }
})();
export function createArtworkRoutes() {
    const router = express.Router();
    /**
   * PUT /api/tracks/:trackId/artwork
   * Store artwork URL for a track
   */ router.put("/tracks/:trackId/artwork", async (req, res)=>{
        try {
            const trackId = decodeURIComponent(req.params.trackId);
            const { artwork_url, source, width, height } = req.body;
            // Validate input
            if (!artwork_url || !source) {
                return res.status(400).json({
                    success: false,
                    error: "Missing required fields: artwork_url and source"
                });
            }
            serverLogger.info(`Storing artwork for track: ${trackId} from source: ${source}`);
            const artworkService = getArtworkStorageService();
            // Store the artwork URL
            const stored = artworkService.storeArtwork(trackId, artwork_url, source, {
                width,
                height
            });
            if (stored) {
                // Optionally download the artwork for local storage
                if (artwork_url.startsWith("http")) {
                    // Download in background, don't wait
                    artworkService.downloadAndStoreArtwork(trackId, artwork_url, source).catch((err)=>serverLogger.error("Background artwork download failed:", err));
                }
                res.status(200).json({
                    success: true,
                    artwork_url,
                    source,
                    cached: true
                });
            } else {
                res.status(500).json({
                    success: false,
                    error: "Failed to store artwork"
                });
            }
        } catch (error) {
            serverLogger.error("Failed to store artwork:", error);
            res.status(500).json({
                success: false,
                error: error instanceof Error ? error.message : "Internal server error"
            });
        }
    });
    /**
   * GET /api/tracks/:trackId/artwork
   * Retrieve artwork URL for a track
   */ router.get("/tracks/:trackId/artwork", async (req, res)=>{
        try {
            const trackId = decodeURIComponent(req.params.trackId);
            const size = req.query.size || "original";
            const artworkService = getArtworkStorageService();
            const storedArtwork = artworkService.getArtwork(trackId);
            if (storedArtwork) {
                let artworkUrl = storedArtwork.artwork_url;
                // If it's a local file and size is requested, resize it
                if (artworkUrl.startsWith("/") && fs.existsSync(artworkUrl) && size !== "original") {
                    artworkUrl = await getResizedArtwork(artworkUrl, size);
                }
                res.status(200).json({
                    success: true,
                    artwork_url: artworkUrl,
                    source: storedArtwork.source,
                    cached: true
                });
            } else {
                // No stored artwork found
                res.status(404).json({
                    success: false,
                    error: "No artwork found for track",
                    cached: false
                });
            }
        } catch (error) {
            serverLogger.error("Failed to retrieve artwork:", error);
            res.status(500).json({
                success: false,
                error: error instanceof Error ? error.message : "Internal server error"
            });
        }
    });
    /**
   * DELETE /api/tracks/:trackId/artwork
   * Remove stored artwork for a track
   */ router.delete("/tracks/:trackId/artwork", async (req, res)=>{
        try {
            const trackId = decodeURIComponent(req.params.trackId);
            const artworkService = getArtworkStorageService();
            // We need to add a delete method to the service
            // For now, we can store a null URL to effectively remove it
            const removed = artworkService.storeArtwork(trackId, "", "deleted");
            res.status(200).json({
                success: removed,
                message: removed ? "Artwork removed" : "Failed to remove artwork"
            });
        } catch (error) {
            serverLogger.error("Failed to delete artwork:", error);
            res.status(500).json({
                success: false,
                error: error instanceof Error ? error.message : "Internal server error"
            });
        }
    });
    /**
   * GET /api/artwork/statistics
   * Get artwork storage statistics
   */ router.get("/artwork/statistics", async (req, res)=>{
        try {
            const artworkService = getArtworkStorageService();
            const stats = artworkService.getStatistics();
            res.status(200).json({
                success: true,
                statistics: stats
            });
        } catch (error) {
            serverLogger.error("Failed to get artwork statistics:", error);
            res.status(500).json({
                success: false,
                error: error instanceof Error ? error.message : "Internal server error"
            });
        }
    });
    /**
   * GET /artwork/:hash
   * Serve artwork file by hash
   */ router.get("/artwork/:hash", async (req, res)=>{
        try {
            const { hash } = req.params;
            const size = req.query.size || "original";
            // Get the artwork service
            const artworkService = getArtworkService();
            let artworkPath = null;
            let format = "jpeg";
            // Check if we have this artwork in our map
            if (artworkService.artworkMap && artworkService.artworkMap.has(hash)) {
                const artworkInfo = artworkService.artworkMap.get(hash);
                artworkPath = artworkInfo.path;
                format = artworkInfo.format || "jpeg";
            }
            // If not in map, check filesystem directly (both artwork-cache and artwork directories)
            if (!artworkPath || !fs.existsSync(artworkPath)) {
                const userDataPath = process.env.ELECTRON_USER_DATA || (await import("../utils/platformPaths.js")).getUserDataPath();
                const cacheDir = path.join(userDataPath, "artwork-cache");
                const legacyDir = path.join(userDataPath, "artwork");
                // Check common extensions in both directories
                const extensions = [
                    "",
                    ".jpg",
                    ".jpeg",
                    ".png",
                    ".webp"
                ];
                for (const ext of extensions){
                    const cachePath = path.join(cacheDir, hash + ext);
                    if (fs.existsSync(cachePath)) {
                        artworkPath = cachePath;
                        format = ext.replace(".", "") || "jpeg";
                        break;
                    }
                    const legacyPath = path.join(legacyDir, hash + ext);
                    if (fs.existsSync(legacyPath)) {
                        artworkPath = legacyPath;
                        format = ext.replace(".", "") || "jpeg";
                        break;
                    }
                }
            }
            // Serve the file if found
            if (artworkPath && fs.existsSync(artworkPath)) {
                // Set proper headers
                res.setHeader("Content-Type", `image/${format}`);
                res.setHeader("Cache-Control", "public, max-age=31536000"); // Cache for 1 year
                // If resizing is requested and sharp is available
                if (size !== "original" && sharp) {
                    try {
                        const resized = await getResizedArtwork(artworkPath, size);
                        return res.sendFile(resized);
                    } catch (err) {
                        // If resize fails, send original
                        serverLogger.warn(`Failed to resize artwork: ${err}`);
                    }
                }
                // Send the original file
                return res.sendFile(artworkPath);
            }
            // Artwork not found
            res.status(404).json({
                error: "Artwork not found"
            });
        } catch (error) {
            serverLogger.error("Failed to serve artwork:", error);
            res.status(500).json({
                error: error instanceof Error ? error.message : "Internal server error"
            });
        }
    });
    /**
   * POST /api/artwork/cleanup
   * Clean up old artwork entries
   */ router.post("/artwork/cleanup", async (req, res)=>{
        try {
            const daysOld = parseInt(req.body.days_old || "30");
            const artworkService = getArtworkStorageService();
            const cleaned = artworkService.cleanupOldArtwork(daysOld);
            res.status(200).json({
                success: true,
                cleaned_entries: cleaned
            });
        } catch (error) {
            serverLogger.error("Failed to cleanup artwork:", error);
            res.status(500).json({
                success: false,
                error: error instanceof Error ? error.message : "Internal server error"
            });
        }
    });
    return router;
}
/**
 * Get resized artwork based on size parameter
 */ async function getResizedArtwork(filePath, size) {
    try {
        const sizes = {
            small: 150,
            medium: 300,
            large: 600,
            xlarge: 1200
        };
        const targetSize = sizes[size] || 300;
        // Generate cache path
        const ext = path.extname(filePath);
        const baseName = path.basename(filePath, ext);
        const dir = path.dirname(filePath);
        const cachedPath = path.join(dir, "cache", `${baseName}_${size}${ext}`);
        // Check if cached version exists
        if (fs.existsSync(cachedPath)) {
            return cachedPath;
        }
        // Ensure cache directory exists
        const cacheDir = path.join(dir, "cache");
        if (!fs.existsSync(cacheDir)) {
            fs.mkdirSync(cacheDir, {
                recursive: true
            });
        }
        // Resize the image if sharp is available
        if (sharp) {
            await sharp(filePath).resize(targetSize, targetSize, {
                fit: "cover",
                position: "center"
            }).toFile(cachedPath);
        } else {
            // If sharp is not available, just copy the original file
            fs.copyFileSync(filePath, cachedPath);
        }
        return cachedPath;
    } catch (error) {
        serverLogger.error("Failed to resize artwork:", error);
        return filePath; // Return original on error
    }
}

//# sourceMappingURL=artworkRoutes.js.map