const fs = require('fs');
const { 
    Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType, 
    Table, TableRow, TableCell, WidthType, BorderStyle, LevelFormat, 
    Header, Footer, PageNumber, ShadingType, VerticalAlign 
} = require('docx');

const specPath = process.argv[2];
const outputPath = process.argv[3];

if (!specPath || !outputPath) {
    console.error("Usage: node generator.js <spec_json_path> <output_docx_path>");
    process.exit(1);
}

let spec;
try {
    const raw = fs.readFileSync(specPath, 'utf8');
    spec = JSON.parse(raw);
} catch (e) {
    console.error("Failed to parse JSON spec:", e.message);
    process.exit(1);
}

const sections = Array.isArray(spec.sections) ? spec.sections : [];
if (sections.length === 0) {
    console.warn("Warning: spec.sections is empty. Report will contain only a title page.");
}

// Design Constants
const BRAND_BLUE = "2E75B5";
const GREY_TEXT = "595959";
const MAIN_FONT = "Arial";
const PAGE_WIDTH_DXA = 12240; // 8.5 inches
const PAGE_HEIGHT_DXA = 15840; // 11 inches
const CONTENT_WIDTH_DXA = 9360; // 8.5" - 2" margins
const BORDER_SINGLE = { style: BorderStyle.SINGLE, size: 6, color: BRAND_BLUE };

function createHeading(text, level = HeadingLevel.HEADING_1) {
    return new Paragraph({
        text: text.toUpperCase(),
        heading: level,
        spacing: { before: 300, after: 150 },
        border: level === HeadingLevel.HEADING_1 ? { bottom: BORDER_SINGLE } : undefined
    });
}

function createBullet(text) {
    return new Paragraph({
        children: [new TextRun({ text: text, size: 22, font: MAIN_FONT })],
        numbering: {
            reference: "bullets",
            level: 0,
        },
        spacing: { after: 100 }
    });
}

function processContent(content) {
    const children = [];
    const text = (content == null) ? ''
        : (typeof content === 'string') ? content
        : JSON.stringify(content, null, 2);

    const lines = text.split('\n');
    lines.forEach(line => {
        const trimmed = line.trim();
        if (!trimmed) return;

        // Detect if line is a bullet
        if (trimmed.startsWith('- ') || trimmed.startsWith('* ') || (trimmed.startsWith('•'))) {
            const bulletText = trimmed.replace(/^[-*•]\s+/, "");
            children.push(createBullet(bulletText));
        } else {
            children.push(new Paragraph({
                children: [new TextRun({ text: trimmed, size: 22, font: MAIN_FONT })],
                spacing: { after: 120 }
            }));
        }
    });
    return children;
}

const doc = new Document({
    styles: {
        default: {
            document: {
                run: { font: MAIN_FONT, size: 24, color: "000000" }
            }
        },
        paragraphStyles: [
            {
                id: "Heading1",
                name: "Heading 1",
                basedOn: "Normal",
                next: "Normal",
                quickFormat: true,
                run: { size: 32, bold: true, color: BRAND_BLUE, font: MAIN_FONT },
                paragraph: { spacing: { before: 400, after: 200 }, outlineLevel: 0 }
            },
            {
                id: "Heading2",
                name: "Heading 2",
                basedOn: "Normal",
                next: "Normal",
                quickFormat: true,
                run: { size: 28, bold: true, color: BRAND_BLUE, font: MAIN_FONT },
                paragraph: { spacing: { before: 300, after: 150 }, outlineLevel: 1 }
            }
        ]
    },
    numbering: {
        config: [
            {
                reference: "bullets",
                levels: [
                    {
                        level: 0,
                        format: LevelFormat.BULLET,
                        text: "•",
                        alignment: AlignmentType.LEFT,
                        style: {
                            paragraph: { indent: { left: 720, hanging: 360 } }
                        }
                    }
                ]
            }
        ]
    },
    sections: [{
        properties: {
            page: {
                size: { width: PAGE_WIDTH_DXA, height: PAGE_HEIGHT_DXA },
                margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 }
            }
        },
        headers: {
            default: new Header({
                children: [
                    new Paragraph({
                        children: [
                            new TextRun({ 
                                text: "INTELLISTREAM MACHINE INTUITION", 
                                bold: true, 
                                size: 18, 
                                color: GREY_TEXT,
                                font: MAIN_FONT 
                            }),
                            new TextRun({ text: "  |  Strategic Intelligence Report", size: 18, color: GREY_TEXT, font: MAIN_FONT })
                        ]
                    })
                ]
            })
        },
        footers: {
            default: new Footer({
                children: [
                    new Paragraph({
                        alignment: AlignmentType.CENTER,
                        children: [
                            new TextRun({ text: "CONFIDENTIAL • Generated by Intellistream AI", size: 16, color: "A6A6A6", font: MAIN_FONT }),
                            new TextRun({ text: " • Page ", size: 16, color: "A6A6A6", font: MAIN_FONT }),
                            new TextRun({ children: [PageNumber.CURRENT], size: 16, color: "A6A6A6", font: MAIN_FONT }),
                            new TextRun({ text: " of ", size: 16, color: "A6A6A6", font: MAIN_FONT }),
                            new TextRun({ children: [PageNumber.TOTAL_PAGES], size: 16, color: "A6A6A6", font: MAIN_FONT })
                        ]
                    })
                ]
            })
        },
        children: [
            // Title Page Hero
            new Paragraph({
                alignment: AlignmentType.CENTER,
                spacing: { before: 800, after: 400 },
                children: [
                    new TextRun({
                        text: (spec.title || "Strategic Intelligence Report").toUpperCase(),
                        bold: true,
                        size: 44,
                        color: BRAND_BLUE,
                        font: MAIN_FONT
                    })
                ]
            }),
            new Paragraph({
                alignment: AlignmentType.CENTER,
                spacing: { after: 800 },
                children: [
                    new TextRun({
                        text: "PROFECUTIVE ANALYSIS & STRATEGIC RECOMMENDATIONS",
                        italics: true,
                        size: 20,
                        color: GREY_TEXT,
                        font: MAIN_FONT
                    })
                ]
            }),
            
            // Sections
            ...(sections).flatMap(s => {
                const header = createHeading((s && s.header) || "Section");
                const body = processContent(s ? s.content : "");
                return [header, ...body];
            })
        ]
    }]
});

Packer.toBuffer(doc).then((buffer) => {
    fs.writeFileSync(outputPath, buffer);
    console.log("Professional Report generated successfully at: " + outputPath);
}).catch(err => {
    console.error("Packer Error:", err);
    process.exit(1);
});
