Spaces:
Paused

File size: 59,347 Bytes
60c146e
 
 
510332d
60c146e
 
 
0ba1efd
 
60c146e
34c81a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c146e
 
 
 
 
 
 
 
 
0ba1efd
 
 
 
 
 
 
510332d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ba1efd
 
 
 
 
 
 
 
268ef75
0ba1efd
 
 
 
 
 
35f49fd
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
 
510332d
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d3aceb
 
 
 
 
35f49fd
60c146e
35f49fd
 
 
268ef75
35f49fd
 
 
810780c
 
 
35f49fd
810780c
35f49fd
 
 
 
 
810780c
35f49fd
 
 
 
810780c
35f49fd
 
 
 
810780c
35f49fd
 
 
 
 
 
810780c
 
 
 
 
 
 
510332d
 
 
 
 
 
 
 
 
 
 
 
 
 
810780c
 
 
 
510332d
810780c
 
 
 
 
 
35f49fd
 
 
 
 
60c146e
268ef75
1d3aceb
268ef75
60c146e
268ef75
60c146e
 
1d3aceb
0ba1efd
1d3aceb
 
 
268ef75
1d3aceb
 
 
 
 
 
 
 
 
 
 
60c146e
1d3aceb
 
 
 
60c146e
1d3aceb
 
 
 
 
60c146e
1d3aceb
 
 
 
 
60c146e
 
 
 
 
 
 
 
 
 
510332d
 
 
 
 
 
 
 
 
 
 
 
 
 
60c146e
 
 
 
510332d
60c146e
 
 
 
1d3aceb
60c146e
 
 
 
1d3aceb
60c146e
 
 
 
 
 
 
 
 
 
 
1d3aceb
 
 
 
 
 
60c146e
 
 
 
 
 
 
268ef75
1d3aceb
 
268ef75
1d3aceb
60c146e
1d3aceb
60c146e
 
1d3aceb
0ba1efd
1d3aceb
 
35f49fd
 
 
 
268ef75
35f49fd
 
 
60c146e
1d3aceb
60c146e
1d3aceb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c146e
 
 
 
0787112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c146e
 
b1a72b6
60c146e
 
 
 
 
 
 
 
 
 
 
 
 
f1249fe
60c146e
f1249fe
 
 
 
 
 
 
 
 
60c146e
 
f1249fe
60c146e
 
0ba1efd
 
60c146e
 
 
 
 
 
 
 
f1249fe
60c146e
 
 
 
1d3aceb
 
0ba1efd
 
 
1d3aceb
 
60c146e
34c81a9
 
 
 
 
 
 
 
 
 
60c146e
 
 
 
 
1d3aceb
 
 
 
 
 
 
 
 
 
 
34c81a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c146e
1d3aceb
 
0ba1efd
 
 
 
 
 
 
 
 
 
1d3aceb
 
0ba1efd
 
af5facd
0ba1efd
 
 
 
 
 
 
 
 
 
 
 
 
 
af5facd
1d3aceb
 
 
35f49fd
 
 
 
 
 
0787112
35f49fd
0787112
34c81a9
 
60c146e
 
0ba1efd
af5facd
 
0ba1efd
 
 
af5facd
 
510332d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af5facd
510332d
af5facd
 
0ba1efd
af5facd
 
 
 
 
 
 
60c146e
 
34c81a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60c146e
 
 
 
34c81a9
0787112
 
 
60c146e
1d3aceb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c81a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510332d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c81a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d3aceb
34c81a9
 
 
 
 
1d3aceb
60c146e
 
1d3aceb
34c81a9
 
 
 
 
 
60c146e
 
34c81a9
60c146e
 
 
 
34c81a9
 
60c146e
 
 
be69847
60c146e
 
0787112
60c146e
0787112
 
 
 
 
 
 
 
 
 
60c146e
 
 
 
 
1d3aceb
60c146e
 
 
 
34c81a9
0787112
 
 
60c146e
1d3aceb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c81a9
60c146e
 
1d3aceb
 
 
be69847
60c146e
 
34c81a9
60c146e
 
 
 
 
af5facd
60c146e
 
34c81a9
60c146e
0ba1efd
60c146e
 
 
 
 
 
af5facd
34c81a9
af5facd
60c146e
34c81a9
1d3aceb
af5facd
1d3aceb
34c81a9
 
 
 
0787112
 
60c146e
 
af5facd
 
 
 
 
 
 
510332d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af5facd
 
 
510332d
af5facd
 
 
 
 
 
 
 
 
34c81a9
b1a72b6
60c146e
 
 
 
 
 
 
 
 
 
0ba1efd
60c146e
 
 
1d3aceb
60c146e
1d3aceb
60c146e
1d3aceb
60c146e
1d3aceb
 
 
 
 
 
 
 
 
 
 
60c146e
b1a72b6
60c146e
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
import { GoogleGenerativeAI } from '@google/generative-ai';
import { getFileObject } from '../utils/storageUtils.js';
import * as cheerio from 'cheerio';
import { convertToPdf } from '../utils/docConverter.js';

// Initialize Gemini
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
export const quickModel = genAI.getGenerativeModel({ model: "gemini-3.1-pro-preview" });
export const powerfulModel = genAI.getGenerativeModel({ model: "gemini-3.1-pro-preview" });

// ─── DIAGRAM / DRAWING INTELLIGENCE ────────────────────────────────────────

/**
 * Keywords that trigger full A4 architectural/technical drawing mode.
 */
const ARCH_DRAWING_KEYWORDS = [
    'architectural drawing', 'floor plan', 'site plan', 'structural drawing',
    'elevation drawing', 'section drawing', 'building plan', 'layout plan',
    'construction drawing', 'civil drawing', 'electrical layout', 'plumbing layout',
    'landscape plan', 'master plan', 'plot plan', 'foundation plan'
];

/**
 * Analyses a plan item and tender context to determine diagram needs.
 * Returns { needsSvg, needs3d, isArchitecturalDrawing }
 */
const detectDiagramNeeds = (planItem, tender) => {
    const text = [
        planItem.docName || '',
        planItem.purpose || '',
        (planItem.outline?.sections || []).join(' '),
        (planItem.outline?.keyPoints || []).join(' '),
        tender?.analysis?.announcementType || '',
        tender?.userPrompt || ''
    ].join(' ').toLowerCase();

    const isArchitecturalDrawing = ARCH_DRAWING_KEYWORDS.some(kw => text.includes(kw));

    const needsSvg = isArchitecturalDrawing || [
        'org chart', 'organisational chart', 'organizational chart', 'organogram',
        'gantt', 'timeline', 'work plan', 'schedule', 'flowchart', 'process flow',
        'workflow', 'methodology diagram', 'logical framework', 'logframe',
        'results framework', 'theory of change', 'network diagram',
        'site layout', 'infrastructure', 'system architecture', 'data flow'
    ].some(kw => text.includes(kw));

    const needs3d = isArchitecturalDrawing || [
        '3d model', 'three-dimensional', 'perspective view', 'isometric',
        'building model', 'structural model', '3d render'
    ].some(kw => text.includes(kw));

    return { needsSvg, needs3d, isArchitecturalDrawing };
};

/**
 * The Three.js importmap injected into every generated document <head>.
 * Allows AI-generated <script type="module"> blocks to import from 'three'.
 */
const THREE_IMPORTMAP = `
    <script type="importmap">
    {
      "imports": {
        "three": "https://cdn.jsdelivr.net/npm/three@0.165.0/build/three.module.js",
        "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.165.0/examples/jsm/"
      }
    }
    </script>`;

/**
 * Extra CSS injected into every generated document for diagrams/drawings.
 */
const DIAGRAM_CSS = `
        /* ── Diagram / Drawing Styles ── */
        .diagram-block { margin: 28px 0; text-align: center; }
        .diagram-block svg { max-width: 100%; height: auto; border: 1px solid #e2e8f0; border-radius: 4px; background: #fff; }
        .diagram-block figcaption { font-size: 12px; color: #718096; margin-top: 6px; font-style: italic; }
        .three-canvas-wrap { margin: 28px 0; }
        .three-canvas-wrap canvas { width: 100% !important; max-width: 800px; height: 420px !important; border: 1px solid #e2e8f0; border-radius: 4px; display: block; margin: 0 auto; }
        /* A4 Architectural Drawing */
        .a4-drawing-page { width: 210mm; min-height: 297mm; margin: 20px auto; background: white; border: 1px solid #ccc; box-shadow: 0 4px 24px rgba(0,0,0,0.12); position: relative; padding: 0; }
        .a4-drawing-page svg { width: 210mm; height: 297mm; display: block; }
        @media print {
            body { background: white !important; }
            .page { box-shadow: none !important; margin: 0 !important; padding: 10mm !important; max-width: 100% !important; }
            .a4-drawing-page { box-shadow: none; margin: 0; border: none; }
            @page { size: A4 portrait; margin: 8mm; }
        }`;

/**
 * Pre-print hook script: converts Three.js canvases to static images before printing.
 */
const PRINT_HOOK_SCRIPT = `
    <script>
    window.addEventListener('beforeprint', () => {
        document.querySelectorAll('canvas[data-threejs]').forEach(canvas => {
            const img = document.createElement('img');
            img.src = canvas.toDataURL('image/png');
            img.style.cssText = canvas.style.cssText;
            img.style.maxWidth = '100%';
            canvas.parentNode.insertBefore(img, canvas);
            canvas.style.display = 'none';
            canvas._printImg = img;
        });
    });
    window.addEventListener('afterprint', () => {
        document.querySelectorAll('canvas[data-threejs]').forEach(canvas => {
            if (canvas._printImg) { canvas._printImg.remove(); canvas.style.display = ''; }
        });
    });
    </script>`;

// Helper to convert R2 Stream to Buffer (for Gemini)
const streamToBuffer = async (stream) => {
    const chunks = [];
    for await (const chunk of stream) {
        chunks.push(chunk);
    }
    return Buffer.concat(chunks);
};

/**
 * Label an uploaded file using AI β€” called immediately after upload.
 * Returns { label, description, documentCategory, detectedCompanyName }
 * documentCategory: 'call' (RFP/TOR/EOI/bid docs) | 'company' (applicant docs) | 'other'
 */
export const labelUploadedFile = async (fileBuffer, mimeType, originalName) => {
    try {
        let currentBuffer = fileBuffer;
        let currentMimeType = mimeType;
        
        if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
            currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
            originalName.endsWith('.docx') || originalName.endsWith('.xlsx')) {
            try {
                console.log(`Converting ${originalName} to PDF for Gemini labeling...`);
                currentBuffer = await convertToPdf(currentBuffer, currentMimeType, originalName);
                currentMimeType = 'application/pdf';
            } catch (err) {
                console.warn(`Conversion failed for ${originalName}, passing original. Error:`, err);
            }
        }

        const prompt = `
        TASK: Analyze this document and classify it for a tender/proposal management system.
        Original filename: "${originalName}"

        Determine ALL of the following:
        1. A short TYPE label (e.g. "Call Document - RFP", "Terms of Reference", "EOI Announcement", "Bid Form / Template",
           "Company Profile", "CV - [Person Name]", "Past Project Report", "Financial Statement", "Registration Certificate",
           "Tax Certificate", "Audited Accounts", "Authorization Letter", "Technical Specification", "Company Brochure", etc.)
        2. A 1-3 sentence description of the content.
        3. Whether this is a CALL document or a COMPANY document:
           - "call" = Documents FROM the procuring entity: RFP, RFQ, EOI, TOR, Tender Notice, Invitation to Bid, Bid Forms, 
             Mandatory Templates, Blank Forms, Evaluation Criteria documents, Addenda, Clarifications
           - "company" = Documents BELONGING TO the applicant/bidder: Company Profile, CVs, Past Project Reports,
             Financial Statements, Bank Statements, Audited Accounts, Registration Certificates, Tax Clearance, 
             Business Licenses, Authorization Letters, References, Company Brochures, Capability Statements, 
             Staff Qualifications, Insurance Certificates, Past applications and proposals
           - "other" = anything that doesn't clearly fit either category
        4. If it is a "company" document, try to detect the company/organization name from its content (or null if not found).

        Return ONLY a valid JSON object, no markdown:
        {
          "label": "Short type label",
          "description": "1-2 sentence summary",
          "documentCategory": "call" | "company" | "other",
          "detectedCompanyName": "Company Name Ltd" | null
        }
        `;

        const result = await quickModel.generateContent([
            prompt,
            { inlineData: { data: currentBuffer.toString('base64'), mimeType: currentMimeType } }
        ]);
        let text = result.response.text().replace(/```json/g, '').replace(/```/g, '').trim();
        const parsed = JSON.parse(text);
        return {
            label: parsed.label || 'Uploaded Document',
            description: parsed.description || '',
            documentCategory: ['call', 'company', 'other'].includes(parsed.documentCategory) ? parsed.documentCategory : 'other',
            detectedCompanyName: parsed.detectedCompanyName || null
        };
    } catch (error) {
        console.warn('File labeling failed for', originalName, ':', error.message);
        return { label: 'Uploaded Document', description: '', documentCategory: 'other', detectedCompanyName: null };
    }
};

/**
 * STEP 1: Deep analysis of the announcement documents.
 * Determines type, extracts requirements, detects MISSING documents (templates/forms),
 * and generates strategy questions.
 */
export const analyzeDocuments = async (files, userPrompt = '', promptOnly = false) => {
    try {
        // ── PROMPT-ONLY MODE: No documents uploaded β€” use user description alone ──
        if (promptOnly || files.length === 0) {
            const promptOnlyInstruction = `
            I need your help to draft a document as described below:

            USER DESCRIPTION:
            ${userPrompt || 'No description provided.'}
            
            ATTACHED DOCUMENTS:
            Please also review any attached documents to understand the context. The user may have attached documents they want you to work on or reference.

            Based on this description and the attached documents:

            TASK 1 - DETERMINE DOCUMENT TYPE:
            Identify the type of document/proposal the user wants to create (e.g. "Company Profile", "Technical Proposal for IT Consultancy", "Grant Proposal for Youth Program", "Cover Letter", "Business Plan", etc.).

            TASK 2 - GENERATE STRATEGY QUESTIONS:
            Generate 4-6 targeted clarifying questions to gather the information needed to draft a high-quality, detailed version of this document. Focus on specific content, data, and evidence needed. DO NOT ask for information that is already clearly provided in the attached documents or the user description.

            Return STRICTLY valid JSON (no markdown, no wrapping, just raw JSON):
            {
                "announcement_type": "Type of document to be drafted (e.g. 'Company Profile', 'Technical Proposal')",
                "summary": "3-4 sentence summary describing exactly what document will be created and its purpose, incorporating insights from the attached documents if any.",
                "is_complete": true,
                "missing_documents": [],
                "authority_documents": [],
                "strategy_questions": [
                    "Specific question 1 to gather key content not found in the documents",
                    "Specific question 2",
                    "Specific question 3",
                    "Specific question 4"
                ]
            }
            `;
            
            const aiInputs = [promptOnlyInstruction];

            if (files && files.length > 0) {
                for (const file of files) {
                    console.log(`Fetching ${file.originalName} from R2 (Prompt-Only Mode)...`);
                    const { Body } = await getFileObject(file.storageKey);
                    let buffer = await streamToBuffer(Body);
                    let currentMimeType = file.mimeType;

                    if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                        currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                        file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
                        try {
                            console.log(`Converting ${file.originalName} to PDF for Gemini analysis (Prompt-Only)...`);
                            buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
                            currentMimeType = 'application/pdf';
                        } catch (err) {
                            console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
                        }
                    }

                    aiInputs.push({
                        inlineData: {
                            data: buffer.toString('base64'),
                            mimeType: currentMimeType
                        }
                    });
                }
            }

            const result = await quickModel.generateContent(aiInputs);
            let text = result.response.text().replace(/```json/g, '').replace(/```/g, '').trim();
            return JSON.parse(text);
        }

        // ── STANDARD MODE: Analyze uploaded documents ──
        const prompt = `
        I need your help to analyze the uploaded documents and help me draft response documents to the call/EOI/Grant/Tender, etc. in question.
        
        Please thoroughly read and analyze the attached announcement documents (which may be an RFP, EOI, Call for Proposals, Grant Application, Tender Notice, Expression of Interest, TOR, or similar).

        CUSTOM CONTEXT / INSTRUCTIONS (pay close attention):
        ${userPrompt ? userPrompt : "None provided."}

        TASK 1 - IDENTIFY THE ANNOUNCEMENT TYPE:
        First, please determine exactly what type of competitive announcement this is. Be specific (e.g., "Restricted Tender for Supply of Medical Equipment", "Open Call for EOI for IT Consultancy Services", "Grant Application for Youth Empowerment Program").

        TASK 2 - DEEP DOCUMENT REVIEW:
        Read all documents meticulously. Understand the evaluation criteria, scope of work, qualification requirements, format requirements, mandatory forms, and special instructions from any TOR or similar documents.
        CRITICAL: If any uploaded call document contains an APPLICATION FORM, TEMPLATE, or SPECIFIC FORMAT requirements β€” note them exactly. All drafted documents MUST follow those templates/forms if provided, exactly.

        TASK 3 - IDENTIFY MISSING DOCUMENTS:
        Check if the applicant has provided ALL necessary documents from the announcement itself. Specifically look for:
        - Required templates (e.g., "Please use the attached Budget Template", "Fill in Form A")
        - Mandatory forms referenced in the RFP but not attached
        - Technical specifications or addenda that should accompany the main document
        - Reference letters format, CV templates, company profile templates specified by the issuer
        Only list documents that are explicitly REQUIRED by the announcement and appear to be missing from the uploaded set.

        TASK 4 - AUTHORITY DOCUMENTS:
        List documents the applicant must obtain from external sources (Tax Clearance, Business Registration, Audited Financials, etc.).

        TASK 5 - STRATEGY QUESTIONS:
        Generate 4-6 high-impact strategy questions to build a winning proposal. Focus on the applicant's unique strengths, measurable past performance, team qualifications, and how they align with the evaluator's priorities. Do NOT ask for generic info like company name.

        Return STRICTLY valid JSON (no markdown, no wrapping, just raw JSON):
        {
            "announcement_type": "Specific type of announcement (e.g. Open Tender - Supply of Laboratory Equipment)",
            "summary": "Detailed 3-4 sentence summary covering: what is needed, who is the issuer, key deadlines/requirements, and evaluation focus.",
            "is_complete": boolean,
            "missing_documents": ["Only documents REQUIRED by the announcement that are not in the uploaded set, e.g. 'Budget Template Form B (referenced on page 4 of TOR)'"],
            "authority_documents": ["Documents applicant must obtain externally, e.g. 'Valid Tax Clearance Certificate'"],
            "strategy_questions": [
                "Question 1 focused on demonstrating relevant past experience with measurable outcomes",
                "Question 2 focused on technical approach or methodology",
                "Question 3 focused on team qualifications and capacity",
                "Question 4 focused on unique value proposition vs competitors",
                "Question 5 focused on local presence or partnerships if applicable"
            ]
        }
        `;

        // 1. Fetch files from R2 and format for Gemini
        const aiInputs = [prompt];

        for (const file of files) {
            console.log(`Fetching ${file.originalName} from R2...`);
            const { Body } = await getFileObject(file.storageKey);
            let buffer = await streamToBuffer(Body);
            let currentMimeType = file.mimeType;

            if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
                try {
                    console.log(`Converting ${file.originalName} to PDF for Gemini analysis...`);
                    buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
                    currentMimeType = 'application/pdf';
                } catch (err) {
                    console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
                }
            }

            aiInputs.push({
                inlineData: {
                    data: buffer.toString('base64'),
                    mimeType: currentMimeType
                }
            });
        }

        console.log("Sending to Gemini for deep analysis...");
        const result = await powerfulModel.generateContent(aiInputs);
        const response = result.response;
        let text = response.text();

        // Cleanup JSON
        text = text.replace(/```json/g, '').replace(/```/g, '').trim();

        return JSON.parse(text);

    } catch (error) {
        console.error("AI Analysis Error:", error);
        throw new Error("Failed to analyze documents");
    }
};


/**
 * STEP 2: Generate a detailed drafting plan with section-level outlines.
 * References the announcement instructions (TOR, evaluation criteria) to determine
 * exactly what documents and structure are needed.
 */
export const generateDraftingPlan = async (tenderSummary, announcementType, requirements, questions, answers, files) => {
    try {
        let qaContext = "";
        questions.forEach((q, i) => {
            qaContext += `Q: ${q.question}\nA: ${answers[i]}\n\n`;
        });

        const prompt = `
        I need your help to analyze the uploaded documents and help me draft a response documents writing plan to the call/EOI/Grant/Tender, etc. in question.

        ANNOUNCEMENT TYPE: ${announcementType}
        ANNOUNCEMENT SUMMARY: ${tenderSummary}
        REQUIREMENTS & AUTHORITY DOCS: ${JSON.stringify(requirements)}
        
        APPLICANT STRATEGY (their answers):
        ${qaContext}

        TASK:
        Based on the announcement type, requirements, and the applicant's strategy, please create a COMPREHENSIVE, DETAILED drafting plan for ALL documents that need to be created to submit a winning, compliant proposal.

        CRITICAL RULES:
        1. TEMPLATE/FORM ADHERENCE IS THE HIGHEST PRIORITY. If any call document contains an application form, a template, or explicit format instructions, ALL drafted documents MUST mirror that exact structure β€” use the same headings, same section order, same table formats, same field names. Do not invent your own section ordering if the announcement specifies one.
        2. Follow the announcement's format instructions STRICTLY. If the TOR says "Technical Proposal must have: Executive Summary, Methodology, Team CVs, Work Plan" β€” use exactly those sections in exactly that order.
        3. If a blank application form is uploaded, treat each form field as a required section in the drafting plan.
        4. For each document, provide a DETAILED outline with specific sections, estimated paragraph count, and key points to cover.
        5. Break large documents (anything over 3 pages should be a separate document section) into parts using this EXACT syntax: "Technical Proposal - Executive Summary - Part 1", "Technical Proposal - Methodology - Part 2" etc. so they can be merged.
        6. Do NOT include documents the applicant must obtain themselves (like Tax Clearance). ONLY documents that require writing/drafting.
        7. Each document section should be detailed enough for a writer to produce a complete, detailed, and professional draft.
        8. Return a valid JSON array.

        Output Format (strict JSON array):
        [
            {
                "docName": "Document name using Part syntax if multi-part (e.g. Technical Proposal - Executive Summary & Methodology - Part 1)",
                "purpose": "What this document/part covers and its role in the proposal",
                "outline": {
                    "sections": [
                        "1. Executive Summary (2 paragraphs: project understanding + our value proposition)",
                        "2. Background & Context (1 paragraph: issuer context, 1 paragraph: problem statement)",
                        "3. Proposed Methodology (3-4 paragraphs covering each work stream)",
                        "4. Innovation & Differentiation (1 paragraph)"
                    ],
                    "estimatedPages": 4,
                    "estimatedParagraphs": 9,
                    "keyPoints": [
                        "Highlight ${answers[0] ? answers[0].substring(0, 60) + '...' : 'applicant strengths'}",
                        "Use evaluation criteria language from the announcement",
                        "Reference specific requirements from the TOR"
                    ]
                }
            }
        ]
        `;

        const aiInputs = [prompt];

        if (files && files.length > 0) {
            for (const file of files) {
                try {
                    const { Body } = await getFileObject(file.storageKey);
                    let buffer = await streamToBuffer(Body);
                    let currentMimeType = file.mimeType;

                    if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                        currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                        file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
                        try {
                            buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
                            currentMimeType = 'application/pdf';
                        } catch (err) {
                            console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
                        }
                    }

                    aiInputs.push({
                        inlineData: { data: buffer.toString('base64'), mimeType: currentMimeType }
                    });
                } catch (fileErr) {
                    console.warn(`Could not attach ${file.originalName}:`, fileErr.message);
                }
            }
        }

        const result = await powerfulModel.generateContent(aiInputs);
        const response = result.response;
        let text = response.text();

        text = text.replace(/```json/g, '').replace(/```/g, '').trim();

        return JSON.parse(text);

    } catch (error) {
        console.error("Plan Generation Error:", error);
        throw new Error("Failed to generate drafting plan");
    }
};

export const checkExistingDocuments = async (generatedPlan, uploadedFileNames) => {
    try {
        const prompt = `
        You are a STRICT document matching assistant. Your job is to identify which AI-drafted document plans are ALREADY SATISFIED by an uploaded file.

        CRITICAL RULES β€” err strongly on the side of NOT matching:
        - Only mark a Required Document as satisfied if an uploaded file is CLEARLY and OBVIOUSLY the EXACT completed final version of that specific document.
        - Call documents such as RFPs, TORs, EOIs, templates, blank forms, guidelines, requests, and announcements DO NOT satisfy any Required Document β€” they are input reference material.
        - Reference documents, company profiles, CVs, and past work samples DO NOT satisfy a Required Document unless the Required Document is literally asking for that exact thing (e.g. Required Document = "Company Profile" and uploaded file = "Company_Profile.pdf").
        - A required document that needs to be WRITTEN (e.g. Technical Proposal, Cover Letter, Methodology, Budget, Staffing Plan, Work Plan, Financial Proposal, Capability Statement) is NEVER satisfied by an uploaded reference file.
        - When in doubt, DO NOT match. It is better to re-draft something than to silently skip it.
        - ONLY match when the file name is an unmistakably direct match to the exact required document name AND the file is clearly the final completed version.

        Required Documents (to be drafted by AI):
        ${JSON.stringify(generatedPlan.map(d => d.docName))}

        Uploaded Files (reference material provided by user):
        ${JSON.stringify(uploadedFileNames)}

        Please return a strictly valid JSON array of strings containing ONLY the Required Documents that are genuinely, obviously already completed in one of the uploaded files.
        If nothing is clearly satisfied, please return an empty array [].
        Do NOT include markdown formatting, just the raw JSON array.
        `;

        const result = await quickModel.generateContent(prompt);
        let text = result.response.text().replace(/```json/g, '').replace(/```/g, '').trim();
        return JSON.parse(text);
    } catch (error) {
        console.error("Check Existing Docs Error:", error);
        return []; // Safe default β€” draft everything
    }
};


/**
 * STEP 3: Generate document content using the detailed outline from the plan.
 * Separates call docs (bid requirements) from company docs (applicant data).
 * Only attaches company docs that match the tender's companyName, so a user
 * working for multiple companies never mixes up their documents.
 */
export const generateDocumentContent = async (tender, planItem) => {
    try {
        // ── Detect what kind of visual content this document needs ──
        const diagramFlags = detectDiagramNeeds(planItem, tender);
        const { needsSvg, needs3d, isArchitecturalDrawing } = diagramFlags;

        // Route architectural drawings to the specialist function
        if (isArchitecturalDrawing) {
            console.log(`πŸ“ Architectural drawing detected: "${planItem.docName}" β€” using specialist generator`);
            return await generateArchitecturalDrawing(tender, planItem);
        }

        let strategyContext = "";
        tender.analysis.strategyQuestions.forEach(q => {
            strategyContext += `Q: ${q.question}\nA: ${q.answer}\n\n`;
        });

        const outlineInstructions = planItem.outline ? `
        DOCUMENT OUTLINE (follow this PRECISELY - do not deviate):
        Sections to cover:
        ${planItem.outline.sections ? planItem.outline.sections.join('\n') : 'As appropriate for this document type'}
        
        Target: ~${planItem.outline.estimatedPages || 2} pages, ~${planItem.outline.estimatedParagraphs || 6} paragraphs
        
        Key Points to emphasize:
        ${planItem.outline.keyPoints ? planItem.outline.keyPoints.join('\n') : 'Based on applicant strategy'}
        ` : '';

        // ── Build diagram instructions to inject into the prompt ──
        let diagramInstructions = '';
        if (needsSvg || needs3d) {
            diagramInstructions = `
        ─── DIAGRAM & VISUALISATION REQUIREMENTS ───
        This document requires visual diagrams. You MUST include them as described below.
        The HTML wrapper already loads Three.js via importmap, so all script tags will work.

        ${needsSvg ? `SVG DIAGRAMS (REQUIRED):
        - Where relevant (org charts, Gantt charts, process flows, timelines, work plans, site layouts, data flows),
          embed DETAILED inline SVG diagrams directly in the HTML body.
        - Wrap each in: <figure class="diagram-block"><svg viewBox="0 0 800 500" xmlns="http://www.w3.org/2000/svg" style="width:100%;max-width:800px">...</svg><figcaption>Figure N: Description β€” Scale/Units if applicable</figcaption></figure>
        - SVG must be FULLY DRAWN β€” no placeholder boxes. Include labels, axis ticks, arrows, legend if needed.
        - Gantt charts: horizontal bars per task on a time axis with month labels.
        - Org charts: rectangles connected by lines, with role titles and names.
        - Flowcharts: rounded rects for steps, diamonds for decisions, arrows for flow.
        - Use colours: header/title bars #2b6cb0, accents #38a169, gridlines #e2e8f0, text #1a202c.` : ''}

        ${needs3d ? `THREE.JS 3D VISUALISATION (include if it adds value β€” e.g. system architecture, building structure, infrastructure layout):
        - Add a <div class="three-canvas-wrap"><canvas id="three-canvas" data-threejs></canvas></div> where appropriate.
        - Follow it with a <script type="module"> that imports from 'three' (already in importmap).
        - Build a simple but meaningful scene: e.g. OrbitControls-enabled isometric view of a building block or network node graph.
        - Camera: orthographic or perspective. Lighting: AmbientLight + DirectionalLight. Background: 0xf0f4f8.
        - Keep the script self-contained. Use THREE.BoxGeometry, MeshStandardMaterial, etc.
        - CRITICAL FOR PDF EXPORT: When creating the WebGLRenderer, you MUST set preserveDrawingBuffer: true so the canvas can be captured as a PNG for PDF export:
          const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('three-canvas'), antialias: true, preserveDrawingBuffer: true });
        - Example import: import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js';` : ''}
        `;
        }

        // ── File filtering: separate by category, filter company docs by company name ──
        const projectCompany = (tender.companyName || '').toLowerCase().trim();
        const callDocs = [];
        const companyDocs = [];
        const otherDocs = [];

        for (const file of (tender.inputFiles || [])) {
            const cat = file.documentCategory || 'other';
            if (cat === 'call') {
                callDocs.push(file);
            } else if (cat === 'company') {
                // If project has a company name set, only include matching company docs
                if (projectCompany) {
                    const fileCompany = (file.companyName || '').toLowerCase().trim();
                    const matches = !fileCompany ||
                        fileCompany.includes(projectCompany) ||
                        projectCompany.includes(fileCompany);
                    if (matches) companyDocs.push(file);
                    else console.log(`Skipping ${file.originalName} β€” belongs to "${file.companyName}", project is "${tender.companyName}"`);
                } else {
                    companyDocs.push(file); // No filter if company not set
                }
            } else {
                otherDocs.push(file);
            }
        }

        const filesToUse = [...callDocs, ...companyDocs, ...otherDocs];

        // Build file manifest for prompt
        const callManifest = callDocs.map((f, i) => `  πŸ“’ ${i + 1}. [${f.aiLabel}] "${f.originalName}" β€” ${f.aiDescription || '(no description)'}`).join('\n');
        const companyManifest = companyDocs.map((f, i) => `  🏒 ${i + 1}. [${f.aiLabel}] "${f.originalName}" β€” ${f.aiDescription || '(no description)'}`).join('\n');
        const otherManifest = otherDocs.map((f, i) => `  πŸ“„ ${i + 1}. [${f.aiLabel}] "${f.originalName}" β€” ${f.aiDescription || '(no description)'}`).join('\n');

        const prompt = `
        ROLE: Expert Proposal Writer with 20+ years of experience in ${tender.analysis.announcementType || 'competitive procurement'}.
        
        TASK: Please write the COMPLETE, DETAILED content for: "${planItem.docName}"
        PURPOSE: ${planItem.purpose || 'As specified by the announcement'}

        ─── ANNOUNCEMENT CONTEXT ───
        Type: ${tender.analysis.announcementType || 'Tender/RFP'}
        Title: ${tender.title}
        Bidding Company: ${tender.companyName || '(see company documents)'}
        Summary: ${tender.analysis.summary}

        ─── APPLICANT STRATEGY (Q&A) ───
        ${strategyContext}

        ─── ATTACHED FILES ───
        The following documents are attached inline to this request:

        πŸ“’ CALL / BID DOCUMENTS (from the procuring entity):
        ${callManifest || '  (none)'}
        β†’ Use these to understand: requirements, evaluation criteria, scoring rubrics, submission format, TOR instructions.

        🏒 COMPANY DOCUMENTS β€” ${tender.companyName || 'Applicant'} (belonging to the bidding company):
        ${companyManifest || '  (none)'}
        β†’ Extract REAL specific data from these: company name, registration number, directors, key staff names &
          qualifications, specific past projects (names, locations, dates, contract values, outcomes), financial turnover,
          certifications, licenses, client references.

        ${otherManifest ? `πŸ“„ OTHER DOCUMENTS:\n        ${otherManifest}` : ''}

        CRITICAL: Do NOT use generic placeholders if the real data exists in the attached documents.
        Only use [COMPANY NAME], [AMOUNT], [DATE] etc. for data genuinely absent from all files.

        ${outlineInstructions}

        WRITING RULES:
        1. Write COMPLETE, professional, detailed content β€” not a generic template.
        2. CRITICAL β€” TEMPLATE/FORM ADHERENCE: If a call document contains an application form or template, reproduce its structure EXACTLY. Use the same field/section names, same table columns, same ordering. Fill in every field or section from the company data and strategy Q&A.
        3. Use the bidding company's actual data from the attached company documents (real names, real projects, real figures, real registration numbers).
        4. Mirror the call document's terminology and evaluation criteria language throughout.
        5. Use clear headings (h2, h3), well-developed paragraphs, semi-professional tone.
        6. For budgets/schedules/BOQs use proper HTML tables with realistic but well-reasoned figures.
        7. Use semantic HTML (NO <html>/<head>/<body> tags). You MAY use Tailwind CSS classes and Google Material Icons (<span class="material-icons">icon_name</span>) to create a beautiful, modern design, especially if the user requests a specific style.
        8. Every section must be substantive with specific evidence, examples, and measurable outcomes β€” never leave placeholder text if real data is available.
        9. CUSTOM FONTS: If the user requests a specific font, or if you choose to use a custom Google Font, you MUST include its \`<style>@import url('https://fonts.googleapis.com/css2?family=Font+Name&display=swap');</style>\` tag at the very top of your HTML output and apply it using inline styles or Tailwind classes.

        ${diagramInstructions}
        `;

        // Attach files inline to the AI request
        const aiInputs = [prompt];

        if (filesToUse.length > 0) {
            console.log(`Attaching ${filesToUse.length} file(s) β€” ${callDocs.length} call, ${companyDocs.length} company, ${otherDocs.length} other`);
            for (const file of filesToUse) {
                try {
                    const { Body } = await getFileObject(file.storageKey);
                    let buffer = await streamToBuffer(Body);
                    let currentMimeType = file.mimeType;

                    if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                        currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                        file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
                        try {
                            console.log(`Converting ${file.originalName} to PDF for Gemini generation...`);
                            buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
                            currentMimeType = 'application/pdf';
                        } catch (err) {
                            console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
                        }
                    }

                    aiInputs.push({
                        inlineData: { data: buffer.toString('base64'), mimeType: currentMimeType }
                    });
                } catch (fileErr) {
                    console.warn(`Could not attach ${file.originalName}:`, fileErr.message);
                }
            }
        } else {
            console.log('No input files to attach β€” generating from strategy context only.');
        }

        const result = await powerfulModel.generateContent(aiInputs);
        let rawHtml = result.response.text().replace(/```html/g, '').replace(/```/g, '').trim();

        // WRAPPER: Full document with Three.js importmap + diagram CSS
        const fullHtml = buildDocumentWrapper(planItem.docName, tender.title, tender.companyName, rawHtml, diagramFlags);
        return fullHtml;

    } catch (error) {
        console.error(`Error generating ${planItem.docName}:`, error);
        throw new Error("AI Generation Failed");
    }
};

/**
 * Builds the full self-contained HTML wrapper for a generated document.
 * Always includes the Three.js importmap and diagram CSS so SVG/canvas
 * content rendered by the AI works out-of-the-box in the iframe and prints correctly.
 */
const buildDocumentWrapper = (docName, tenderTitle, companyName, bodyContent, diagramFlags = {}) => {
    const archClass = diagramFlags.isArchitecturalDrawing ? ' arch-drawing-doc' : '';
    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${docName}</title>${THREE_IMPORTMAP}
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Merriweather:wght@400;700&family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Inter', sans-serif; background: #f4f5f7; color: #1a202c; line-height: 1.7; }
        .page { max-width: 850px; margin: 30px auto; padding: 60px 70px; background: white; box-shadow: 0 4px 24px rgba(0,0,0,0.08); border-radius: 4px; }
        h1 { font-family: 'Merriweather', serif; font-size: 24px; color: #1a365d; margin-bottom: 8px; padding-bottom: 16px; border-bottom: 3px solid #2b6cb0; }
        h2 { font-family: 'Merriweather', serif; font-size: 18px; color: #2b6cb0; margin-top: 32px; margin-bottom: 12px; padding-bottom: 6px; border-bottom: 1px solid #bee3f8; }
        h3 { font-size: 15px; font-weight: 700; color: #2d3748; margin-top: 20px; margin-bottom: 8px; }
        h4 { font-size: 14px; font-weight: 600; color: #4a5568; margin-top: 16px; margin-bottom: 6px; }
        p { margin-bottom: 14px; font-size: 14px; text-align: justify; }
        ul, ol { margin: 10px 0 14px 24px; font-size: 14px; }
        li { margin-bottom: 6px; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }
        thead { background: #2b6cb0; color: white; }
        th { padding: 10px 12px; text-align: left; font-weight: 600; }
        td { padding: 9px 12px; border-bottom: 1px solid #e2e8f0; }
        tr:nth-child(even) { background: #f7fafc; }
        strong { color: #2d3748; }
        .doc-meta { font-size: 12px; color: #718096; margin-bottom: 30px; padding-bottom: 16px; border-bottom: 1px solid #e2e8f0; }
        ${DIAGRAM_CSS}
    </style>
</head>
<body class="${archClass}">
    <div class="page">
        <h1>${docName}</h1>
        <div class="doc-meta">Document for: ${tenderTitle} &nbsp;|&nbsp; Generated by ${companyName}</div>
        ${bodyContent}
    </div>
${PRINT_HOOK_SCRIPT}
</body>
</html>`;
};

/**
 * SPECIALIST: Generate a detailed A4-sized architectural / technical drawing.
 * Called automatically when detectDiagramNeeds() flags isArchitecturalDrawing.
 */
export const generateArchitecturalDrawing = async (tender, planItem) => {
    try {
        let strategyContext = "";
        (tender.analysis?.strategyQuestions || []).forEach(q => {
            strategyContext += `Q: ${q.question}\nA: ${q.answer}\n\n`;
        });

        const prompt = `
        ROLE: Professional Architectural Drafter β€” 20+ years technical drawing experience.

        TASK: Produce a COMPLETE, DETAILED architectural/technical drawing for: "${planItem.docName}"
        PURPOSE: ${planItem.purpose || 'Technical drawing as specified'}

        PROJECT CONTEXT:
        Project Title: ${tender.title}
        Client/Company: ${tender.companyName || '[Company]'}
        Announcement Type: ${tender.analysis?.announcementType || 'Construction/Design Project'}

        STRATEGY CONTEXT:
        ${strategyContext || '(Infer from project title and purpose)'}

        OUTPUT: Raw HTML content ONLY (no <html>/<head>/<body> wrapper tags).
        The surrounding document already has Three.js loaded via importmap.

        MANDATORY CONTENT:

        1. MAIN SVG DRAWING β€” A4 proportions (viewBox="0 0 794 1123"):
           - Outer border: <rect x="10" y="10" width="774" height="1103" fill="none" stroke="#1a202c" stroke-width="2"/>
           - Inner margin line: <rect x="25" y="25" width="744" height="1068" fill="none" stroke="#1a202c" stroke-width="0.5"/>
           
        2. TITLE BLOCK (inside SVG, at bottom ~y=1010 to y=1103):
           Render as bordered cells with <rect> + <text>:
           - "PROJECT:" ${tender.title}
           - "DRAWING TITLE:" ${planItem.docName}  
           - "DRAWN BY:" ${tender.companyName || 'AI Drafter'}
           - "DATE:" ${new Date().toLocaleDateString('en-GB')}
           - "SCALE:" 1:100 (or as appropriate)
           - "REV:" A   "DWG NO:" DWG-001
           
        3. MAIN DRAWING (SVG drawing area, y=25 to y=1005):
           Draw a realistic, detailed plan appropriate for: "${planItem.docName}"
           
           For FLOOR PLANS / BUILDING PLANS use:
           - Walls: <line> or <rect> with stroke-width="5" stroke="#1a202c" β€” show actual room layout
           - Windows: double parallel lines + centre gap + opening arc (stroke="#4a90d9" stroke-width="1.5")
           - Doors: single line + quarter-circle arc showing swing direction
           - Room labels: <text> centred in each room (font-family="Arial" font-size="11" fill="#2d3748")
           - Grid reference bubbles at grid intersections (circles with A/B/C and 1/2/3 labels)
           - Dimension lines: <line stroke="#e53e3e" stroke-width="0.7"> with tick marks + <text> measurements
           - Hatching in wall thickness: <pattern> with diagonal lines or cross-hatch
           
           For SITE PLANS use roads, plot boundaries, building footprints, vegetation symbols, north arrow.
           For STRUCTURAL DRAWINGS use beam/column grid, member sizes annotated.
           For ELECTRICAL LAYOUTS use socket/light symbols, circuit lines, distribution board.
           
        4. NORTH ARROW (top-right, around x=720 y=80):
           SVG north arrow: circle + arrow pointing up + "N" text label.
           
        5. SCALE BAR (bottom-left of drawing area, around x=35 y=990):
           Graphic bar: alternating black/white segments, labelled 0-5-10-20m.

        6. THREE.JS 3D INSET (placed BELOW the SVG, outside the drawing frame):
           <div class="three-canvas-wrap" style="padding:20px;text-align:center;background:#f7fafc;border-top:2px solid #e2e8f0;margin-top:0">
             <p style="font-size:12px;color:#4a5568;margin-bottom:8px;font-family:Arial">&#x1F4D0; 3D Perspective View &mdash; Interactive (Drag to Rotate)</p>
             <canvas id="arch-3d-canvas" data-threejs style="width:100%;max-width:700px;height:360px;border:1px solid #d0d8e8;border-radius:4px"></canvas>
           </div>
           <script type="module">
           import * as THREE from 'three';
           import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
           // IMPORTANT: preserveDrawingBuffer MUST be true so canvas.toDataURL() works for PDF export.
           // Create renderer like this:
           // const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('arch-3d-canvas'), antialias: true, preserveDrawingBuffer: true });
           // Build an appropriate 3D scene: walls extruded from floor plan, roof slab, columns.
           // Materials: floor=0xd4c5a9, walls=0xe8e0d0, roof=0x8b7355, glass=0xa8d8f0.
           // Add GridHelper, AmbientLight(0xffffff,0.6), DirectionalLight(0xffffff,0.8).
           // OrbitControls for interactivity. Auto-resize on window resize.
           // Isometric-style camera start: camera.position.set(15, 12, 15); camera.lookAt(0,0,0).
           </script>

        DRAWING QUALITY RULES:
        - Every element must be drawn β€” no empty placeholders.
        - All text must be legible (min 9px in SVG).
        - Use colour coding: structure=#1a202c, annotations=#e53e3e, services=#4a90d9, vegetation=#38a169.
        - Include a LEGEND box if using symbols.
        - The Three.js script must be FULLY written and functional β€” not just pseudocode.

        Output ONLY the HTML elements (SVG + Three.js div+script). No wrapper tags.
        `;

        const aiInputs = [prompt];

        for (const file of (tender.inputFiles || [])) {
            if (['call', 'other'].includes(file.documentCategory)) {
                try {
                    const { Body } = await getFileObject(file.storageKey);
                    let buffer = await streamToBuffer(Body);
                    let currentMimeType = file.mimeType;

                    if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                        currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                        file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
                        try {
                            console.log(`Converting ${file.originalName} to PDF for Gemini drawing...`);
                            buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
                            currentMimeType = 'application/pdf';
                        } catch (err) {
                            console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
                        }
                    }

                    aiInputs.push({ inlineData: { data: buffer.toString('base64'), mimeType: currentMimeType } });
                } catch (_) { /* skip unreadable */ }
            }
        }

        const result = await powerfulModel.generateContent(aiInputs);
        let rawHtml = result.response.text().replace(/```html/g, '').replace(/```/g, '').trim();

        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${planItem.docName} β€” Technical Drawing</title>${THREE_IMPORTMAP}
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: Arial, sans-serif; background: #dde1ea; }
        .arch-header { text-align:center; padding: 14px 20px; font-size: 12px; color: #4a5568; background: #f7fafc; border-bottom: 1px solid #d0d8e8; display:flex; justify-content:space-between; align-items:center; }
        .arch-header strong { color: #1a365d; font-size: 14px; }
        .arch-header .note { font-size: 11px; color: #a0aec0; }
        .drawing-container { width: 210mm; margin: 18px auto; background: white; box-shadow: 0 6px 32px rgba(0,0,0,0.22); border: 1px solid #b0b8c8; }
        .drawing-container svg { display: block; width: 100%; height: auto; }
        .three-canvas-wrap canvas { width: 100% !important; max-width: 700px; height: 360px !important; display: block; margin: 0 auto; }
        @media print {
            body { background: white !important; }
            .arch-header { display: none; }
            .drawing-container { box-shadow: none; margin: 0; border: none; width: 100%; }
            .three-canvas-wrap { display: none; }
            @page { size: A4 portrait; margin: 5mm; }
        }
    </style>
</head>
<body>
    <div class="arch-header">
        <strong>&#x1F4D0; ${planItem.docName}</strong>
        <span>${tender.title} &nbsp;&bull;&nbsp; ${tender.companyName || 'Technical Drawing'}</span>
        <span class="note">3D view: drag to rotate &bull; prints as line drawing only</span>
    </div>
    <div class="drawing-container">
        ${rawHtml}
    </div>
${PRINT_HOOK_SCRIPT}
</body>
</html>`;

    } catch (error) {
        console.error(`Architectural drawing error for ${planItem.docName}:`, error);
        throw new Error('Architectural drawing generation failed');
    }
};

export const mergeHtmlParts = (htmlParts, title, companyName) => {
    let combinedBodyContent = "";

    htmlParts.forEach((html, index) => {
        const $ = cheerio.load(html);
        
        $('h1, h2, h3').each((i, el) => {
            const text = $(el).text();
            $(el).text(text.replace(/\s*-\s*Part\s*\d+/i, ''));
        });

        if (index > 0) {
            $('.doc-meta').remove();
        }

        let content = $('.page').html();
        if (!content) content = $('body').html();
        combinedBodyContent += `\n<div class="merged-section mb-8">${content || ""}</div>\n`;
    });

    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${title}</title>${THREE_IMPORTMAP}
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Merriweather:wght@400;700&family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: 'Inter', sans-serif; background: #f4f5f7; color: #1a202c; line-height: 1.7; }
        .page { max-width: 850px; margin: 30px auto; padding: 60px 70px; background: white; box-shadow: 0 4px 24px rgba(0,0,0,0.08); border-radius: 4px; }
        h1 { font-family: 'Merriweather', serif; font-size: 24px; color: #1a365d; margin-bottom: 8px; padding-bottom: 16px; border-bottom: 3px solid #2b6cb0; }
        h2 { font-family: 'Merriweather', serif; font-size: 18px; color: #2b6cb0; margin-top: 32px; margin-bottom: 12px; padding-bottom: 6px; border-bottom: 1px solid #bee3f8; }
        h3 { font-size: 15px; font-weight: 700; color: #2d3748; margin-top: 20px; margin-bottom: 8px; }
        h4 { font-size: 14px; font-weight: 600; color: #4a5568; margin-top: 16px; margin-bottom: 6px; }
        p { margin-bottom: 14px; font-size: 14px; text-align: justify; }
        ul, ol { margin: 10px 0 14px 24px; font-size: 14px; }
        li { margin-bottom: 6px; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }
        thead { background: #2b6cb0; color: white; }
        th { padding: 10px 12px; text-align: left; font-weight: 600; }
        td { padding: 9px 12px; border-bottom: 1px solid #e2e8f0; }
        tr:nth-child(even) { background: #f7fafc; }
        strong { color: #2d3748; }
        .doc-meta { font-size: 12px; color: #718096; margin-bottom: 30px; padding-bottom: 16px; border-bottom: 1px solid #e2e8f0; }
        .merged-section + .merged-section { border-top: 2px dashed #e2e8f0; padding-top: 30px; margin-top: 20px; }
        ${DIAGRAM_CSS}
    </style>
</head>
<body>
    <div class="page">
        <h1>${title} (Complete Document)</h1>
        <div class="doc-meta">Combined document &nbsp;|&nbsp; Generated by ${companyName}</div>
        ${combinedBodyContent}
    </div>
${PRINT_HOOK_SCRIPT}
</body>
</html>`;
};


export const refineDocumentContent = async (tender, currentContent, instruction) => {
    try {
        const prompt = `
        ROLE: Expert Proposal Editor and Technical Document Specialist.
        
        TASK: Please rewrite/update and improve the following HTML document based on the user's specific instruction.
        
        USER INSTRUCTION: "${instruction}"
        
        CURRENT CONTENT (HTML):
        ${currentContent}
        
        ATTACHED FILES GUIDE:
        Evaluate the attached files to incorporate real, specific data requested by the user instructions.

        RULES:
        1. Maintain the full HTML structure (h1, h2, h3, p, ul, table, etc.).
        2. ONLY output the complete, valid HTML content. No markdown, no code fences.
        3. Implement the requested changes thoroughly and specifically, using real facts and data from attached documents when requested.
        4. Keep what is working well; only change what the instruction says.
        5. Ensure the output is still complete β€” do not truncate.
        6. CRITICAL β€” PRESERVE ALL SVG DIAGRAMS: If the document contains inline <svg> diagram blocks, preserve them exactly unless the instruction specifically asks to modify or add diagrams. You may update data values or labels within SVGs if the instruction asks for it.
        7. CRITICAL β€” PRESERVE THREE.JS SCRIPTS: If the document contains <script type="module"> Three.js scenes, preserve them unless the instruction asks to change the 3D view.
        8. If the instruction asks to ADD a diagram (Gantt, org chart, floor plan, 3D view), generate a complete, detailed SVG or Three.js block as appropriate. Follow the same diagram conventions: SVG wrapped in <figure class="diagram-block">, Three.js canvas with data-threejs attribute.
        9. CUSTOM FONTS: If the user requests a specific font, include its \`<link href='https://fonts.googleapis.com/css2?family=Font+Name&display=swap' rel='stylesheet'>\` tag in the <head> of the document, and apply it using CSS/Tailwind.
        10. The output must remain a complete self-contained HTML document with all original <head> content (importmap, styles) intact.
        `;

        const aiInputs = [prompt];

        if (tender && tender.inputFiles && tender.inputFiles.length > 0) {
            console.log(`Attaching ${tender.inputFiles.length} file(s) to document refinement...`);
            for (const file of tender.inputFiles) {
                try {
                    const { Body } = await getFileObject(file.storageKey);
                    let buffer = await streamToBuffer(Body);
                    let currentMimeType = file.mimeType;

                    if (currentMimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || 
                        currentMimeType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                        file.originalName.endsWith('.docx') || file.originalName.endsWith('.xlsx')) {
                        try {
                            console.log(`Converting ${file.originalName} to PDF for Gemini refinement...`);
                            buffer = await convertToPdf(buffer, currentMimeType, file.originalName);
                            currentMimeType = 'application/pdf';
                        } catch (err) {
                            console.warn(`Conversion failed for ${file.originalName}, passing original. Error:`, err);
                        }
                    }

                    aiInputs.push({
                        inlineData: {
                            data: buffer.toString('base64'),
                            mimeType: currentMimeType
                        }
                    });
                } catch (fileErr) {
                    console.warn(`Could not attach file ${file.originalName} for refinement:`, fileErr.message);
                }
            }
        }

        const result = await powerfulModel.generateContent(aiInputs);
        let html = result.response.text();

        return html.replace(/```html/g, '').replace(/```/g, '').trim();

    } catch (error) {
        console.error("Refinement Error:", error);
        throw new Error("Failed to refine document");
    }
};

export const generateSubmissionInstructions = async (tender, documentsWithLinks) => {
    const prompt = `
    TASK: Please create a detailed Step-by-Step Submission Guide for this ${tender.analysis.announcementType || 'tender'}.
    
    CONTEXT:
    Title: ${tender.title}
    Announcement Type: ${tender.analysis.announcementType}
    Requirements: ${JSON.stringify(tender.analysis.requirements)}
    Missing Docs to Gather: ${JSON.stringify(tender.analysis.missingDocuments)}

    AI-Generated Documents with Download Links: ${JSON.stringify(documentsWithLinks)}
     
    OUTPUT:
    Return clean HTML with numbered steps (<ol>/<li>) covering exactly what the user needs to do to submit:
    1. Documents to print and how many copies
    2. Documents to sign and where
    3. Physical or digital submission steps
    4. Deadline reminders
    5. Any other critical steps from the announcement

    IMPORTANT: For any AI-generated documents mentioned, provide actual HTML clickable links using the provided URLs.
    Use <a href="..." target="_blank" style="color:#2b6cb0; text-decoration:underline;">...</a> for links.
    Provide both PDF and Word options where applicable.
    `;

    const result = await powerfulModel.generateContent(prompt);
    return result.response.text().replace(/```html/g, '').replace(/```/g, '').trim();
};