"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const promises_1 = __importDefault(require("fs/promises"));
const httpValue_1 = require("../utils/httpValue");
const traceUploadLimit_1 = require("../services/traceUploadLimit");
class TraceController {
    constructor() {
        this.uploadTrace = async (req, res) => {
            try {
                if (!req.file) {
                    const error = {
                        error: 'No file uploaded',
                        details: 'Please upload a .perfetto trace file',
                    };
                    return res.status(400).json(error);
                }
                const file = req.file;
                // Removed file extension validation - accept all files
                console.log(`Uploading file: ${file.originalname}, size: ${file.size} bytes`);
                const maxSize = (0, traceUploadLimit_1.resolveTraceUploadLimitBytes)();
                if (file.size > maxSize) {
                    const error = {
                        error: 'File too large',
                        details: `Maximum file size is ${maxSize / 1024 / 1024}MB`,
                    };
                    return res.status(400).json(error);
                }
                // Move file to upload directory
                const fileName = `${Date.now()}-${file.originalname}`;
                const filePath = path_1.default.join(this.uploadDir, fileName);
                await promises_1.default.rename(file.path, filePath);
                // Return file info
                res.json({
                    fileId: fileName,
                    fileName: file.originalname,
                    fileSize: file.size,
                    filePath: filePath,
                    uploadTime: new Date().toISOString(),
                });
            }
            catch (error) {
                console.error('Error uploading trace:', error);
                const errorResponse = {
                    error: 'Internal server error',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        this.analyzeTrace = async (req, res) => {
            res.status(410).json({
                success: false,
                code: 'TRACE_ANALYZE_DEPRECATED',
                error: '/api/trace/analyze has been removed',
                details: 'Use AgentRuntime unified flow: upload with /api/traces/* and analyze with /api/agent/v1/analyze.',
                migration: {
                    upload: [
                        'POST /api/traces/upload (multipart, file=<trace>)',
                        'GET /api/traces/:id (optional verification)',
                    ],
                    analyze: 'POST /api/agent/v1/analyze',
                },
                removedAt: '2026-02-22',
            });
        };
        this.getTraceInfo = async (req, res) => {
            try {
                const fileId = (0, httpValue_1.toSingleString)(req.params.fileId);
                if (!fileId) {
                    const error = {
                        error: 'Missing file ID',
                        details: 'Please provide a file ID',
                    };
                    return res.status(400).json(error);
                }
                const filePath = path_1.default.join(this.uploadDir, fileId);
                try {
                    const stats = await promises_1.default.stat(filePath);
                    res.json({
                        fileId,
                        fileName: fileId,
                        fileSize: stats.size,
                        createdAt: stats.birthtime,
                        modifiedAt: stats.mtime,
                    });
                }
                catch {
                    const error = {
                        error: 'File not found',
                        details: 'The requested trace file does not exist',
                    };
                    return res.status(404).json(error);
                }
            }
            catch (error) {
                console.error('Error getting trace info:', error);
                const errorResponse = {
                    error: 'Internal server error',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        this.deleteTrace = async (req, res) => {
            try {
                const fileId = (0, httpValue_1.toSingleString)(req.params.fileId);
                if (!fileId) {
                    const error = {
                        error: 'Missing file ID',
                        details: 'Please provide a file ID',
                    };
                    return res.status(400).json(error);
                }
                const filePath = path_1.default.join(this.uploadDir, fileId);
                try {
                    await promises_1.default.unlink(filePath);
                    res.json({
                        message: 'Trace file deleted successfully',
                        fileId,
                    });
                }
                catch {
                    const error = {
                        error: 'File not found',
                        details: 'The requested trace file does not exist',
                    };
                    return res.status(404).json(error);
                }
            }
            catch (error) {
                console.error('Error deleting trace:', error);
                const errorResponse = {
                    error: 'Internal server error',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        this.downloadTrace = async (req, res) => {
            try {
                const fileId = (0, httpValue_1.toSingleString)(req.params.fileId);
                if (!fileId) {
                    const error = {
                        error: 'Missing file ID',
                        details: 'Please provide a file ID',
                    };
                    return res.status(400).json(error);
                }
                const filePath = path_1.default.join(this.uploadDir, fileId);
                try {
                    // Check if file exists
                    await promises_1.default.access(filePath);
                    // Get file stats
                    const stats = await promises_1.default.stat(filePath);
                    // Set appropriate headers
                    res.setHeader('Content-Type', 'application/octet-stream');
                    res.setHeader('Content-Length', stats.size);
                    res.setHeader('Content-Disposition', `attachment; filename="${fileId.replace(/^\d+-/, '')}"`);
                    // Create read stream and pipe to response
                    const fileStream = require('fs').createReadStream(filePath);
                    fileStream.pipe(res);
                    fileStream.on('error', (error) => {
                        console.error('Error streaming file:', error);
                        if (!res.headersSent) {
                            res.status(500).json({
                                error: 'Internal server error',
                                details: 'Error streaming file',
                            });
                        }
                    });
                }
                catch {
                    const error = {
                        error: 'File not found',
                        details: 'The requested trace file does not exist',
                    };
                    return res.status(404).json(error);
                }
            }
            catch (error) {
                console.error('Error downloading trace:', error);
                const errorResponse = {
                    error: 'Internal server error',
                    details: error instanceof Error ? error.message : 'Unknown error',
                };
                res.status(500).json(errorResponse);
            }
        };
        this.uploadDir = process.env.UPLOAD_DIR || './uploads';
        this.ensureUploadDir();
    }
    async ensureUploadDir() {
        try {
            await promises_1.default.access(this.uploadDir);
        }
        catch {
            await promises_1.default.mkdir(this.uploadDir, { recursive: true });
        }
    }
}
exports.default = TraceController;
//# sourceMappingURL=traceController.js.map