File size: 33,196 Bytes
e60c00e
 
 
525d347
bd5de4f
bf9a234
67360ee
 
10eded2
5f9453e
0a1b210
9f4cd2a
 
bf9a234
2c24f0a
234506b
 
9f4cd2a
 
e60c00e
2c24f0a
 
 
 
 
e60c00e
234506b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e34874a
06b2f8b
 
 
cb6077d
83fcc35
5d37246
1e75abc
5d37246
1e75abc
5d37246
1e75abc
83fcc35
 
cb6077d
 
2bef542
 
 
 
 
 
 
 
 
 
 
62cf3f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf9a234
cc1a429
 
62cf3f2
 
cc1a429
 
62cf3f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc1a429
 
 
 
62cf3f2
 
 
cc1a429
 
 
 
62cf3f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392b6fc
62cf3f2
 
 
 
 
 
 
 
 
 
 
 
 
 
21c6284
62cf3f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27430be
06b2f8b
f21f4b0
 
 
 
27430be
f21f4b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10eded2
 
f21f4b0
 
2bef542
 
 
 
62cf3f2
27430be
10eded2
2bef542
 
27430be
2bef542
 
27430be
2bef542
 
27430be
2bef542
 
27430be
2bef542
 
27430be
2bef542
 
27430be
2bef542
 
 
27430be
2bef542
 
 
 
 
 
 
 
 
 
 
 
 
 
27430be
2bef542
27430be
 
 
2bef542
 
 
62cf3f2
 
 
7073225
2bef542
7946627
 
 
 
 
 
 
 
 
 
 
 
 
06b2f8b
18e8106
 
 
4aef3ed
 
 
 
 
 
 
 
 
 
 
 
18e8106
 
 
 
4aef3ed
 
 
18e8106
 
 
 
4aef3ed
7946627
234506b
 
9341c86
7038ced
62cf3f2
 
 
 
 
 
 
 
 
4699f5b
392b6fc
d212a64
 
18e8106
 
 
 
 
d212a64
7eacc0a
 
4aef3ed
732ae7b
18e8106
7eacc0a
18e8106
d212a64
18e8106
9341c86
d1d0218
 
18e8106
 
 
 
 
 
 
9341c86
d1d0218
 
 
9acc52c
 
4aef3ed
d1d0218
 
18e8106
67360ee
e34874a
d212a64
 
 
 
 
 
 
7038ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174db07
7038ced
 
 
 
62cf3f2
3a85524
234506b
 
 
 
 
27430be
21c6284
27430be
 
 
234506b
 
 
 
 
 
 
 
27430be
7eacc0a
7e236fd
 
 
392b6fc
27430be
 
234506b
7e236fd
 
 
27430be
 
234506b
27430be
234506b
 
 
 
 
 
 
7e236fd
 
27430be
 
 
7e236fd
 
d555284
 
234506b
 
dabf044
7e236fd
 
 
8aa81e7
7e236fd
 
234506b
 
dabf044
 
 
 
 
 
 
 
 
234506b
8aa81e7
392b6fc
d555284
 
7e236fd
 
 
 
 
dabf044
7e236fd
 
 
 
 
 
d555284
cc1a429
7e236fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dabf044
d555284
7e236fd
 
 
 
 
 
 
 
d555284
392b6fc
7e236fd
d555284
c1813c1
21c6284
 
7e236fd
 
 
 
 
 
 
 
 
21c6284
 
 
 
 
 
 
 
 
2c24f0a
21c6284
d555284
2c24f0a
21c6284
2c24f0a
 
 
 
94cf5e8
 
2c24f0a
94cf5e8
2c24f0a
94cf5e8
2c24f0a
21c6284
2c24f0a
21c6284
2c24f0a
21c6284
94cf5e8
21c6284
2c24f0a
d555284
234506b
d555284
21c6284
 
 
 
d555284
732ae7b
7e236fd
d555284
7e236fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d555284
 
7e236fd
 
 
 
392b6fc
7e236fd
 
 
 
392b6fc
4699f5b
d555284
732ae7b
27430be
732ae7b
 
 
 
 
 
 
7e236fd
 
c1813c1
 
7e236fd
 
 
 
 
c1813c1
 
7e236fd
c1813c1
 
7e236fd
 
 
c1813c1
 
7e236fd
 
d555284
 
cc1a429
3a85524
94cf5e8
 
 
 
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
import base64
import io
import os
import pandas as pd
from docx import Document
from io import BytesIO
import dash
import dash_bootstrap_components as dbc
from dash import html, dcc, Input, Output, State, callback_context, ALL
from dash.dash_table import DataTable
from PyPDF2 import PdfReader
import logging
import threading
import re
import anthropic
import sqlite3
import time

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')

ANTHROPIC_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
anthropic_client = anthropic.Anthropic(api_key=ANTHROPIC_KEY)
CLAUDE3_SONNET_MODEL = "claude-3-7-sonnet-20250219"
CLAUDE3_MAX_CONTEXT_TOKENS = 200_000
CLAUDE3_MAX_OUTPUT_TOKENS = 64_000

DB_PATH = "maiko_dash_docs.sqlite"

def init_db():
    with sqlite3.connect(DB_PATH) as conn:
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS uploaded_docs
                     (doc_type TEXT PRIMARY KEY, doc_content TEXT, file_name TEXT, last_update TIMESTAMP)''')
        c.execute('''CREATE TABLE IF NOT EXISTS generated_docs
                     (doc_type TEXT PRIMARY KEY, doc_content TEXT, last_update TIMESTAMP)''')
        conn.commit()
init_db()

def set_uploaded_doc(doc_type, doc_content, file_name):
    with sqlite3.connect(DB_PATH) as conn:
        c = conn.cursor()
        c.execute('''INSERT OR REPLACE INTO uploaded_docs (doc_type, doc_content, file_name, last_update)
                     VALUES (?, ?, ?, ?)''', (doc_type, doc_content, file_name, time.time()))
        conn.commit()

def get_uploaded_doc(doc_type):
    with sqlite3.connect(DB_PATH) as conn:
        c = conn.cursor()
        c.execute('''SELECT doc_content, file_name FROM uploaded_docs WHERE doc_type=?''', (doc_type,))
        row = c.fetchone()
        if row:
            return row[0], row[1]
        return None, None

def set_generated_doc(doc_type, doc_content):
    with sqlite3.connect(DB_PATH) as conn:
        c = conn.cursor()
        c.execute('''INSERT OR REPLACE INTO generated_docs (doc_type, doc_content, last_update)
                     VALUES (?, ?, ?)''', (doc_type, doc_content, time.time()))
        conn.commit()

def get_generated_doc(doc_type):
    with sqlite3.connect(DB_PATH) as conn:
        c = conn.cursor()
        c.execute('''SELECT doc_content FROM generated_docs WHERE doc_type=?''', (doc_type,))
        row = c.fetchone()
        if row:
            return row[0]
        return None

spreadsheet_types = ["Shred", "Pink Review", "Red Review", "Gold Review", "Virtual Board", "LOE"]
narrative_types = ["Pink", "Red", "Gold"]

document_types = {
    "Shred": "Ignore all other instructions and generate only requirements spreadsheet of the Project Work Statement (PWS) identified by action words like shall, will, perform etc. by pws section, requirement.  Do not write as if you're responding to the proposal.  Its a spreadsheet to distill the requirements, not microhealth's approach",
    "Pink": "Create a highly detailed Pink Team document based on the PWS outline.  Your goal is to be compliant and compelling.  Focus on describing the approach and how it will be done, the steps, workflow, people, processes and technology based on well known industry standards to accomplish the task.  Be sure to demonstrate innovation.",
    "Pink Review": "Ignore all other instructions and generate and evaluate compliance of the Pink Team document against the requirements and output only a spreadsheet of non compliant findings by pws number, the goal of that pws section, what made it non compliant and your recommendations for recovery. you must also take into account section L&M of the document which is the evaluation criteria to be sure we address them.",
    "Red": "Produce a  highly detailed Red Team document based on the Pink Review by pws sections. Your goal is to be compliant and compelling by recovering all the findings in Pink Review. Focus on describing the approach and how it will be done, the steps, workflow, people, processes and technology to accomplish the task. Be sure to refer to research that validates the approach and cite sources with measurable outcomes",
    "Red Review": "Ignore all other instructions and generate and evaluate compliance of the Red Team document against the requirements and output a only a spreadsheet of non compliant findings by pws number, the goal of that pws section, what made it non compliant and your recommendations for recovery. you must also take into account section L&M of the document which is the evaluation criteria to be sure we address them",
    "Gold": "Create a highly detailed Gold Team document based on the PWS response by pws sections. Your goal is to be compliant and compelling by recovering all the findings in Red Review.  Focus on describing the approach and how it will be done, the steps, workflow, people, processes and technology to accomplish the task. Be sure to refer to research that validates the approach and cite sources with measurable outcomes and improve on innovations of the approach",
    "Gold Review": "Ignore all other instructions and generate and perform a final compliance review against the requirements and output only a spreadsheet of non compliant findings by pws number, the goal of that pws section, what made it non compliant and your recommendations for recovery. you must also take into account section L&M of the document which is the evaluation criteria to be sure we address them",
    "Virtual Board": "Ignore all other instructions and generate and based on the requirements and in particular the evaulation criteria, you will evaluate the proposal as if you were a contracting office and provide section by section evaluation as unsatisfactory, satisfactory, good, very good, excellent and why and produce only spreadsheet",
    "LOE": "Ignore all other instructions and generate and generate a Level of Effort (LOE) breakdown and produce only spreadsheet"
}

doc_dependencies = {
    "Pink": {"source": ["shred"], "require": True},
    "Pink Review": {"source": ["pink", "shred"], "require": True},
    "Red": {"source": ["pink_review"], "require": True},
    "Red Review": {"source": ["red", "shred"], "require": True},
    "Gold": {"source": ["red_review"], "require": True},
    "Gold Review": {"source": ["gold", "shred"], "require": True},
    "LOE": {"source": ["gold"], "require": True},
    "Virtual Board": {"source": ["shred"], "require": True},
}

def extract_markdown_tables(md_text):
    tables = []
    lines = md_text.split('\n')
    in_table = False
    table_lines = []
    for line in lines:
        if re.match(r'^\s*\|.*\|\s*$', line):
            in_table = True
            table_lines.append(line)
        elif in_table and (re.match(r'^\s*\|.*\|\s*$', line) or re.match(r'^\s*$', line)):
            table_lines.append(line)
        else:
            if in_table and table_lines:
                tables.append('\n'.join(table_lines))
                table_lines = []
            in_table = False
    if in_table and table_lines:
        tables.append('\n'.join(table_lines))
    return tables

def markdown_table_to_df(md_table):
    lines = [line.strip() for line in md_table.split('\n') if line.strip()]
    if len(lines) < 2:
        return None
    header = [h.strip() for h in lines[0].strip('|').split('|')]
    sep_idx = 1
    while sep_idx < len(lines) and not re.match(r'^\|\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?$', lines[sep_idx]):
        sep_idx += 1
    data_lines = lines[sep_idx+1:] if sep_idx+1 < len(lines) else []
    rows = []
    for row in data_lines:
        if not row.strip() or not row.strip().startswith('|'):
            continue
        cells = [c.strip() for c in row.strip('|').split('|')]
        if len(cells) < len(header):
            cells += [''] * (len(header) - len(cells))
        elif len(cells) > len(header):
            cells = cells[:len(header)]
        rows.append(cells)
    df = pd.DataFrame(rows, columns=header)
    return df

def markdown_table_preview(md_text):
    if not md_text:
        logging.warning("No markdown text provided for preview.")
        return html.Div("No preview available.")
    tables = extract_markdown_tables(md_text)
    if not tables:
        logging.warning("No tables found in markdown text.")
        return html.Div("No tables to preview.")
    table_divs = []
    for i, table in enumerate(tables):
        df = markdown_table_to_df(table)
        if df is not None and not df.empty:
            table_divs.append(
                html.Div([
                    DataTable(
                        columns=[{"name": str(col), "id": str(col)} for col in df.columns],
                        data=df.to_dict('records'),
                        style_table={'overflowX': 'auto'},
                        style_cell={'whiteSpace': 'normal', 'height': 'auto', 'textAlign': 'left', 'fontFamily': 'monospace', 'fontSize': '14px', 'maxWidth': '400px', 'minWidth': '80px', 'wordBreak': 'break-word'},
                        style_header={'fontWeight': 'bold'},
                        page_size=100,
                        id={'type': 'datatable-preview', 'index': i}
                    )
                ], className="mb-4")
            )
        else:
            logging.warning(f"Table {i} could not be parsed into DataFrame.")
    if not table_divs:
        return html.Div("No valid tables to preview.")
    return html.Div(table_divs)

def markdown_narrative_preview(md_text):
    if not md_text:
        logging.warning("No markdown text provided for narrative preview.")
        return html.Div("No preview available.")
    return html.Div(dcc.Markdown(md_text, dangerously_allow_html=True, style={'whiteSpace': 'pre-wrap', 'fontFamily': 'sans-serif'}))

def markdown_tables_to_xlsx(md_text):
    tables = extract_markdown_tables(md_text)
    output = BytesIO()
    with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
        for i, table in enumerate(tables):
            df = markdown_table_to_df(table)
            if df is not None:
                sheet_name = f"Table{i+1}"
                df.to_excel(writer, sheet_name=sheet_name, index=False)
    output.seek(0)
    return output

def strip_markdown(text):
    text = re.sub(r'(\*\*|__)(.*?)\1', r'\2', text)
    text = re.sub(r'(\*|_)(.*?)\1', r'\2', text)
    text = re.sub(r'`{1,3}[^`]*`{1,3}', '', text)
    text = re.sub(r'^#+ ', '', text, flags=re.MULTILINE)
    text = re.sub(r'^> ', '', text, flags=re.MULTILINE)
    text = re.sub(r'!\[.*?\]\(.*?\)', '', text)
    text = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', text)
    text = re.sub(r'^\s*[-*+] ', '', text, flags=re.MULTILINE)
    text = re.sub(r'^\s*\d+\.\s+', '', text, flags=re.MULTILINE)
    text = text.replace('---', '')
    text = text.replace('___', '')
    text = text.replace('***', '')
    return text.strip()

def process_document(contents, filename):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    try:
        if filename.lower().endswith('.docx'):
            doc = Document(BytesIO(decoded))
            text = "\n".join([para.text for para in doc.paragraphs])
            return text
        elif filename.lower().endswith('.pdf'):
            pdf = PdfReader(BytesIO(decoded))
            text = ""
            for page in pdf.pages:
                page_text = page.extract_text()
                if page_text:
                    text += page_text
            return text
        else:
            return f"Unsupported file format: {filename}. Please upload a PDF or DOCX file."
    except Exception as e:
        logging.error(f"Error processing document: {str(e)}")
        return f"Error processing document: {str(e)}"

def file_list_component():
    return html.Div(
        id='file-list-container',
        children=[
            html.Div(id='file-list')
        ]
    )

def get_left_col_content():
    chat_card = dbc.Card(
        dbc.CardBody([
            html.H5("Maiko Chat", className="mb-2"),
            dcc.Loading(
                id="chat-loading",
                type="default",
                children=[
                    dcc.Textarea(
                        id="chat-input",
                        placeholder="Chat with AI to update document...",
                        className="mb-2",
                        style={
                            'whiteSpace':'pre-wrap',
                            'width': '100%',
                            'minHeight': '100px',
                            'maxHeight': '300px',
                            'resize': 'vertical',
                            'overflowY': 'auto'
                        },
                        rows=5,
                        wrap='soft'
                    ),
                    dbc.Row([
                        dbc.Col(
                            dbc.Button("Send", id="btn-send-chat", color="primary", className="mb-3 w-100"),
                            width=6
                        ),
                        dbc.Col(
                            dbc.Button("Clear Chat", id="btn-clear-chat", color="secondary", className="mb-3 w-100"),
                            width=6
                        ),
                    ], className="g-1 mb-2"),
                    html.Div(id="chat-output")
                ]
            )
        ]),
        className="mt-4"
    )
    return [
        html.H4("Proposal Writer", className="mt-3 mb-2", style={'marginBottom': '12px'}),
        html.Hr(style={'marginTop': '8px', 'marginBottom': '16px'}),
        html.Div(
            id='doc-type-buttons'
        ),
        chat_card
    ]

def get_right_col_content(selected_type, store_data):
    controls = []
    if selected_type == "Shred":
        controls.append(
            html.Div([
                dcc.Upload(
                    id={'type': 'upload-doc-type', 'subtype': 'shred', 'index': selected_type},
                    children=html.Div([
                        'Drag and Drop or ',
                        html.A('Select Files')
                    ]),
                    style={
                        'width': '100%',
                        'height': '60px',
                        'lineHeight': '60px',
                        'borderWidth': '1px',
                        'borderStyle': 'dashed',
                        'borderRadius': '5px',
                        'textAlign': 'center',
                        'margin': '10px 0'
                    },
                    multiple=True
                ),
                file_list_component(),
                html.Div(id='uploaded-doc-name-shred')
            ])
        )
    elif selected_type in doc_dependencies:
        sources = doc_dependencies[selected_type]["source"]
        for src in sources:
            label = ""
            loaded_preview = None
            store_var = store_data.get(src)
            doc_name_id = f"uploaded-doc-name-{src}"
            if src == "shred":
                label = "Shred (Requirements)"
                loaded_preview = markdown_table_preview(store_var)
            elif src == "pink":
                label = "Pink Document"
                loaded_preview = markdown_narrative_preview(store_var)
            elif src == "pink_review":
                label = "Pink Review"
                loaded_preview = markdown_table_preview(store_var)
            elif src == "red":
                label = "Red Document"
                loaded_preview = markdown_narrative_preview(store_var)
            elif src == "red_review":
                label = "Red Review"
                loaded_preview = markdown_table_preview(store_var)
            elif src == "gold":
                label = "Gold Document"
                loaded_preview = markdown_narrative_preview(store_var)
            controls.append(html.Div([
                html.Label(f"Upload {label}"),
                dcc.Upload(
                    id={'type': 'upload-doc-type', 'subtype': src, 'index': selected_type},
                    children=html.Div(['Drag and Drop or ', html.A('Select File')]),
                    style={
                        'width': '100%',
                        'height': '60px',
                        'lineHeight': '60px',
                        'borderWidth': '1px',
                        'borderStyle': 'dashed',
                        'borderRadius': '5px',
                        'textAlign': 'center',
                        'margin': '10px 0'
                    },
                    multiple=False
                ),
                dbc.RadioItems(
                    id={'type': 'radio-doc-source', 'subtype': src, 'index': selected_type},
                    options=[
                        {'label': 'Loaded Document', 'value': 'loaded'}
                    ] if store_var else [],
                    value='loaded' if store_var else None,
                    inline=True,
                    className="mb-2"
                ),
                html.Div([
                    html.Div("Loaded Document Preview:", className="mt-2 mb-1"),
                    loaded_preview
                ], style={'marginBottom': '12px'}),
            ], id={'type': f'doc-type-controls-{src}', 'index': selected_type}))
    controls.append(
        dbc.Row([
            dbc.Col(
                dbc.Button("Generate Document", id={'type': 'btn-generate-doc', 'index': selected_type}, color="primary", className="mb-3 w-100"),
                width=6
            ),
            dbc.Col(
                dbc.Button("Download Document", id="btn-download", color="success", className="mb-3 w-100"),
                width=6
            ),
            dcc.Download(id="download-document")
        ], className="mb-2")
    )
    controls.append(html.Hr())
    controls.append(
        dbc.Card(
            dbc.CardBody(
                dcc.Loading(
                    id='preview-loading',
                    type='default',
                    children=html.Div(
                        id='document-preview',
                        style={
                            'height': '100%',
                            'overflowY': 'auto',
                            'overflowX': 'auto',
                            'padding': '8px'
                        }
                    )
                )
            ),
            style={
                'marginBottom': '10px',
                'height': 'calc(100vh - 155px)',
                'maxHeight': '820px',
                'minHeight': '460px',
                'boxSizing': 'border-box'
            }
        )
    )
    return dbc.Card(dbc.CardBody(controls), style={'height': 'calc(100vh - 140px)', 'maxHeight': '820px', 'minHeight': '460px', 'boxSizing': 'border-box'})

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True)

app.layout = dbc.Container([
    dcc.Store(id='selected-doc-type', data="Shred"),
    dcc.Store(id='store-shred'),
    dcc.Store(id='store-pink'),
    dcc.Store(id='store-pink-review'),
    dcc.Store(id='store-red'),
    dcc.Store(id='store-red-review'),
    dcc.Store(id='store-gold'),
    dcc.Store(id='store-gold-review'),
    dcc.Store(id='store-loe'),
    dcc.Store(id='store-virtual-board'),
    dcc.Store(id='store-generated-doc'),
    dcc.Store(id='main-loader-trigger'),
    dbc.Row([
        dbc.Col(
            html.H2(id='main-title', className="mt-3 mb-2", style={'textAlign': 'center', 'width':'100%'}),
            width=12
        )
    ], justify='center'),
    dbc.Row([
        dbc.Col(
            dcc.Loading(
                id="main-progress-dot",
                type="default",
                children=html.Div(id="main-progress-dot-output"),
                style={'display': 'flex', 'justifyContent': 'center', 'alignItems': 'center', 'height':'40px'}
            ),
            width=12
        )
    ], justify='center'),
    dbc.Row([
        dbc.Col(
            dbc.Card(
                dbc.CardBody(get_left_col_content()),
                style={
                    'height': 'calc(100vh - 140px)',
                    'maxHeight': '820px',
                    'minHeight': '460px',
                    'boxSizing': 'border-box'
                }
            ),
            width=3
        ),
        dbc.Col(
            html.Div([
                html.Div(id='right-col-content')
            ], style={'height': 'calc(100vh - 140px)', 'maxHeight': '820px', 'minHeight': '460px', 'boxSizing': 'border-box'}),
            width=9
        )
    ], align='start')
], fluid=True)

@app.callback(
    Output('main-title', 'children'),
    Input('selected-doc-type', 'data')
)
def update_main_title(selected_type):
    return selected_type

@app.callback(
    Output('doc-type-buttons', 'children'),
    Input('selected-doc-type', 'data')
)
def render_doc_type_buttons(selected_type):
    buttons = []
    for doc_type in document_types.keys():
        btn_style = {'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap'}
        btn_class = "mb-2 w-100 text-left custom-button"
        if doc_type == selected_type:
            btn_class += " active-doc-type"
        buttons.append(
            dbc.Button(
                doc_type,
                id={'type': 'btn-doc-type', 'index': doc_type},
                color="link",
                className=btn_class,
                style=btn_style
            )
        )
    return buttons

@app.callback(
    Output('selected-doc-type', 'data'),
    [Input({'type': 'btn-doc-type', 'index': ALL}, 'n_clicks')],
    [State({'type': 'btn-doc-type', 'index': ALL}, 'id')],
    prevent_initial_call=True
)
def update_selected_doc_type(n_clicks_list, btn_ids):
    triggered = callback_context.triggered
    if not triggered or all(x is None for x in n_clicks_list):
        raise dash.exceptions.PreventUpdate
    idx = [i for i, x in enumerate(n_clicks_list) if x]
    if idx:
        selected_type = btn_ids[idx[-1]]['index']
    else:
        selected_type = "Shred"
    logging.info(f"Doc type selected: {selected_type}")
    return selected_type

@app.callback(
    Output('right-col-content', 'children'),
    Input('selected-doc-type', 'data'),
)
def update_right_col(selected_type):
    store_data = {}
    for store_key in ["shred","pink","pink_review","red","red_review","gold","gold_review","loe","virtual_board"]:
        doc_content, _ = get_uploaded_doc(store_key)
        store_data[store_key] = doc_content
    return get_right_col_content(selected_type, store_data)

@app.callback(
    [
        Output('store-shred', 'data'),
        Output('store-pink', 'data'),
        Output('store-pink-review', 'data'),
        Output('store-red', 'data'),
        Output('store-red-review', 'data'),
        Output('store-gold', 'data'),
        Output('store-gold-review', 'data'),
        Output('store-loe', 'data'),
        Output('store-virtual-board', 'data'),
        Output('file-list', 'children'),
        Output('uploaded-doc-name-shred', 'children'),
        Output('document-preview', 'children'),
        Output('store-generated-doc', 'data'),
        Output('download-document', 'data'),
        Output('main-loader-trigger', 'data')
    ],
    [
        Input({'type': 'upload-doc-type', 'subtype': ALL, 'index': ALL}, 'contents'),
        Input({'type': 'btn-generate-doc', 'index': ALL}, 'n_clicks'),
        Input("btn-download", "n_clicks"),
        Input('selected-doc-type', 'data')
    ],
    [
        State({'type': 'upload-doc-type', 'subtype': ALL, 'index': ALL}, 'filename'),
        State('store-shred', 'data'),
        State('store-pink', 'data'),
        State('store-pink-review', 'data'),
        State('store-red', 'data'),
        State('store-red-review', 'data'),
        State('store-gold', 'data'),
        State('store-gold-review', 'data'),
        State('store-loe', 'data'),
        State('store-virtual-board', 'data'),
        State('store-generated-doc', 'data')
    ],
    prevent_initial_call=True
)
def unified_handler(contents_lists, n_clicks_generate_list, n_clicks_download, selected_type,
                    filenames_lists, shred, pink, pink_review, red, red_review, gold, gold_review, loe, virtual_board, prev_generated):
    logging.info(f"unified_handler triggered. Trigger: {callback_context.triggered}")

    stores = [shred, pink, pink_review, red, red_review, gold, gold_review, loe, virtual_board]
    file_list = []
    uploaded_doc_name_shred = dash.no_update
    preview = dash.no_update
    generated_doc = dash.no_update
    download_data = dash.no_update

    ctx = callback_context
    trigger = ctx.triggered[0]['prop_id'] if ctx.triggered else ""

    subtype_map = {
        "shred": 0,
        "pink": 1,
        "pink_review": 2,
        "red": 3,
        "red_review": 4,
        "gold": 5,
        "gold_review": 6,
        "loe": 7,
        "virtual_board": 8
    }

    loader_trigger = time.time()

    # Handle file upload
    if "upload-doc-type" in trigger:
        for i, (contents, filenames) in enumerate(zip(contents_lists, filenames_lists)):
            if contents and filenames:
                id_dict = ctx.inputs_list[0][i]['id']
                subtype = id_dict['subtype']
                idx = subtype_map[subtype]
                if isinstance(contents, str):
                    contents = [contents]
                    filenames = [filenames]
                content = contents[-1]
                name = filenames[-1]
                file_text = process_document(content, name)
                logging.info(f"Processed uploaded file for subtype '{subtype}': {name}")
                logging.info(f"Extracted text from uploaded document (first 500 chars): {file_text[:500]}")
                set_uploaded_doc(subtype, file_text, name)
                stores[idx] = file_text
                if subtype == "shred":
                    file_list = [
                        dbc.Row([
                            dbc.Col(
                                html.Button('×', id={'type': 'remove-file', 'index': name}, style={'marginRight': '5px', 'fontSize': '10px'}),
                                width=1
                            ),
                            dbc.Col(
                                html.Span(name, style={'wordBreak': 'break-all'}),
                                width=11
                            )
                        ], id={'type': 'file-row', 'index': name}, align="center", className="mb-1")
                    ]
                    uploaded_doc_name_shred = name
                # Preview logic with fallback
                if subtype == "shred":
                    preview = markdown_table_preview(file_text)
                elif subtype in ["pink", "red", "gold"]:
                    preview = markdown_narrative_preview(file_text)
                else:
                    preview = markdown_table_preview(file_text)
                generated_doc = dash.no_update
                download_data = dash.no_update
                logging.info("Returning after file upload.")
                return stores + [file_list, uploaded_doc_name_shred, preview, generated_doc, download_data, loader_trigger]

    # Handle document generation
    if any(n_clicks_generate_list):
        logging.info(f"Generating document for type: {selected_type}")
        inputs = {
            "shred": stores[0],
            "pink": stores[1],
            "pink_review": stores[2],
            "red": stores[3],
            "red_review": stores[4],
            "gold": stores[5],
            "gold_review": stores[6],
            "loe": stores[7],
            "virtual_board": stores[8]
        }
        prompt = document_types.get(selected_type, "")
        context = ""
        if selected_type in doc_dependencies:
            for dep in doc_dependencies[selected_type]["source"]:
                context += f"\n\n{dep.upper()}:\n{inputs.get(dep, '')}"
        else:
            context += f"\n\n{inputs.get('shred','')}"
        full_prompt = f"{prompt}\n\n{context}"
        logging.info(f"Prompt sent to Claude 3 (first 1000 chars): {full_prompt[:1000]}")
        result_holder = {}

        def anthropic_thread():
            try:
                message = anthropic_client.messages.create(
                    model=CLAUDE3_SONNET_MODEL,
                    max_tokens=CLAUDE3_MAX_OUTPUT_TOKENS,
                    system="You are a helpful assistant for proposal writing. Always output in markdown, and use markdown tables for spreadsheets if needed.",
                    messages=[
                        {"role": "user", "content": full_prompt}
                    ]
                )
                result_text = message.content[0].text if hasattr(message, "content") and message.content else str(message)
                result_holder['result'] = result_text
                logging.info("Claude 3 document generated successfully.")
            except Exception as e:
                logging.error(f"Error with Claude 3 API: {str(e)}")
                result_holder['result'] = f"Error generating document: {str(e)}"
        t = threading.Thread(target=anthropic_thread)
        t.start()
        t.join(timeout=120)
        generated_doc = result_holder.get('result', 'Error: No document generated.')
        logging.info(f"Claude 3 API returned: {generated_doc[:500]}")

        set_generated_doc(selected_type, generated_doc)
        # Preview with fallback
        if selected_type in spreadsheet_types:
            preview = markdown_table_preview(generated_doc)
        else:
            preview = markdown_narrative_preview(generated_doc)
        logging.info("Returning after document generation.")
        return stores + [file_list, uploaded_doc_name_shred, preview, generated_doc, dash.no_update, loader_trigger]

    # Handle download
    if "btn-download" in trigger:
        doc = prev_generated
        if not doc:
            doc = get_generated_doc(selected_type)
        if not doc:
            if selected_type == "Shred":
                doc = stores[0]
            elif selected_type == "Pink":
                doc = stores[1]
            elif selected_type == "Pink Review":
                doc = stores[2]
            elif selected_type == "Red":
                doc = stores[3]
            elif selected_type == "Red Review":
                doc = stores[4]
            elif selected_type == "Gold":
                doc = stores[5]
            elif selected_type == "Gold Review":
                doc = stores[6]
            elif selected_type == "LOE":
                doc = stores[7]
            elif selected_type == "Virtual Board":
                doc = stores[8]
        if not doc:
            logging.warning("No generated document to download.")
            preview = html.Div("No document loaded or generated.")
            return stores + [file_list, uploaded_doc_name_shred, preview, dash.no_update, dash.no_update, loader_trigger]
        if selected_type in spreadsheet_types:
            xlsx_io = markdown_tables_to_xlsx(doc)
            logging.info("Spreadsheet document prepared for download.")
            download_data = dcc.send_bytes(xlsx_io.getvalue(), filename=f"{selected_type}_output.xlsx")
            return stores + [file_list, uploaded_doc_name_shred, dash.no_update, dash.no_update, download_data, loader_trigger]
        else:
            content = doc.encode('utf-8')
            logging.info("Narrative document prepared for download.")
            download_data = dcc.send_bytes(content, filename=f"{selected_type}_output.md")
            return stores + [file_list, uploaded_doc_name_shred, dash.no_update, dash.no_update, download_data, loader_trigger]

    # Default preview logic
    doc = prev_generated
    if not doc:
        doc = get_generated_doc(selected_type)
    if doc:
        if selected_type in spreadsheet_types:
            preview = markdown_table_preview(doc)
        else:
            preview = markdown_narrative_preview(doc)
    else:
        if selected_type == "Shred" and stores[0]:
            preview = markdown_table_preview(stores[0])
        elif selected_type in spreadsheet_types:
            doc_store = {
                "Pink Review": stores[2],
                "Red Review": stores[4],
                "Gold Review": stores[6],
                "Virtual Board": stores[8],
                "LOE": stores[7]
            }
            doc = doc_store.get(selected_type, "")
            preview = markdown_table_preview(doc)
        elif selected_type in narrative_types:
            doc_store = {
                "Pink": stores[1],
                "Red": stores[3],
                "Gold": stores[5]
            }
            doc = doc_store.get(selected_type, "")
            preview = markdown_narrative_preview(doc)
        else:
            preview = html.Div("No document loaded or generated.")

    return stores + [file_list, uploaded_doc_name_shred, preview, dash.no_update, dash.no_update, loader_trigger]

if __name__ == '__main__':
    print("Starting the Dash application...")
    app.run(debug=True, host='0.0.0.0', port=7860)
    print("Dash application has finished running.")