const PDFDocument = require('pdfkit');
const fs = require('fs');
const path = require('path');

/**
 * Generates a PDF report for Team Progress
 * @param {Object} organization - The organization details (name, settings)
 * @param {Array} data - Array of member progress objects
 * @param {Stream} res - Express response stream to pipe PDF to
 */
const generateProgressReport = (organization, data, res) => {
    const doc = new PDFDocument({ margin: 50 });

    doc.pipe(res);

    // -- Header --
    _drawHeader(doc, organization, 'Team Progress Report');

    // -- Content Table --
    const tableTop = 150;
    const headers = ['Name', 'Role', 'Level', 'XP', 'Tasks', 'Alerts'];
    const colWidths = [120, 70, 50, 60, 60, 60];
    
    let y = tableTop;
    
    // Draw Table Header
    _drawRow(doc, y, headers, colWidths, true);
    y += 20;
    _drawHorizontalLine(doc, y);
    y += 10;

    // Draw Rows
    data.forEach((member) => {
        // distinct styling for rows
        if (y > 700) {
            doc.addPage();
            _drawHeader(doc, organization, 'Team Progress Report (Cont.)');
            y = 150;
            _drawRow(doc, y, headers, colWidths, true);
            y += 20;
            _drawHorizontalLine(doc, y);
            y += 10;
        }

        const rowData = [
            member.name || 'Unknown',
            member.role,
            member.level.toString(),
            member.xp.toString(),
            member.tasks_completed.toString(),
            member.alerts_resolved.toString()
        ];
        
        _drawRow(doc, y, rowData, colWidths, false);
        y += 25;
    });

    // Footer
    _drawFooter(doc);

    doc.end();
};

/**
 * Generates a PDF report for Compliance / Alert Resolution
 * @param {Object} organization 
 * @param {Array} data 
 * @param {Stream} res 
 */
const generateComplianceReport = (organization, data, res) => {
    const doc = new PDFDocument({ margin: 50 });

    doc.pipe(res);

    _drawHeader(doc, organization, 'Compliance & Resolution Report');

    const tableTop = 150;
    // 'Alert Title', 'Severity', 'Investigator', 'Status', 'Time(m)', 'Grade'
    const headers = ['Alert Title', 'Sev.', 'Investigator', 'Status', 'Time', 'Grade'];
    // Adjusted widths to fit page
    const colWidths = [180, 40, 90, 60, 50, 40];
    
    let y = tableTop;
    
    _drawRow(doc, y, headers, colWidths, true);
    y += 20;
    _drawHorizontalLine(doc, y);
    y += 10;

    data.forEach((row) => {
        if (y > 700) {
            doc.addPage();
            _drawHeader(doc, organization, 'Compliance Report (Cont.)');
            y = 150;
            _drawRow(doc, y, headers, colWidths, true);
            y += 20;
            _drawHorizontalLine(doc, y);
            y += 10;
        }

        const rowData = [
            _truncate(row.alert_title, 35),
            (row.severity || 'N/A').substring(0, 3), // Med, Hig, Low
            _truncate(row.investigator, 15),
            row.status,
            (row.resolution_time_mins || 0).toString() + 'm',
            (row.grade !== null && row.grade !== undefined) ? row.grade.toString() : '-'
        ];

        _drawRow(doc, y, rowData, colWidths, false);
        y += 25;
    });

    _drawFooter(doc);

    doc.end();
};

// --- Helper Functions ---

function _drawHeader(doc, org, title) {
    let primaryColor = '#2563eb'; // Default Blue
    try {
        if (org.settings) {
            const settings = typeof org.settings === 'string' ? JSON.parse(org.settings) : org.settings;
            if (settings.primary_color) primaryColor = settings.primary_color;
        }
    } catch (e) {
        console.warn('Failed to parse org settings for PDF:', e);
    }

    // Draw colored bar at top
    doc.rect(0, 0, 612, 50).fill(primaryColor);
    
    doc.fillColor('#FFFFFF')
       .fontSize(20)
       .text(org.name || 'Organization Report', 50, 15);
       
    doc.fillColor('#444444')
       .fontSize(16)
       .text(title, 50, 80)
       .fontSize(10)
       .text(`Generated on: ${new Date().toLocaleDateString()}`, 50, 100)
       .moveDown();

    // Check for logo URL in settings (assuming local relative path for PDFKit to work best, or remote URL)
    // Note: PDFKit needs a file path or buffer for images. Remote URLs need to be fetched first.
    // Simplifying: Ignoring logo image for now to prevent async fetch complexity in this MVP.
}

function _drawRow(doc, y, rowData, widths, isHeader) {
    let x = 50;
    doc.fontSize(isHeader ? 10 : 9)
       .font(isHeader ? 'Helvetica-Bold' : 'Helvetica')
       .fillColor(isHeader ? '#000000' : '#444444');

    rowData.forEach((text, i) => {
        doc.text(text, x, y, { width: widths[i], align: 'left', ellipsis: true });
        x += widths[i];
    });
}

function _drawHorizontalLine(doc, y) {
    doc.strokeColor('#aaaaaa').lineWidth(1).moveTo(50, y).lineTo(550, y).stroke();
}

function _drawFooter(doc) {
    // Add page numbers in a simpler way or just a static footer
    const bottom = doc.page.margins.bottom;
    doc.page.margins.bottom = 0;
    doc.text(
        'InfoSecLabs Business Platform',
        50,
        doc.page.height - 50,
        { align: 'center', color: '#aaaaaa' }
    );
    doc.page.margins.bottom = bottom;
}

function _truncate(str, n) {
    if (!str) return '';
    return str.length > n ? str.substr(0, n - 1) + '...' : str;
}

module.exports = {
    generateProgressReport,
    generateComplianceReport
};
