File size: 38,352 Bytes
c1b7ea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys
import os
import random
import re
import pandas as pd
import streamlit as st
from datetime import date, datetime, timedelta
from io import BytesIO
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from openpyxl.utils import get_column_letter
from openai import OpenAI

# ๋กœ์ปฌ db_sync ๋ชจ๋“ˆ
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import db_sync

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))

# -----------------------------
# Streamlit ๊ธฐ๋ณธ ์„ค์ • & ํ…Œ๋งˆ CSS
# -----------------------------
st.set_page_config(page_title="BeeCare Core Integration", page_icon="๐Ÿ", layout="wide")

st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Noto+Sans+KR:wght@300;400;500;700;900&display=swap');

html, body, [class*="css"], .stApp {
    font-family: 'Inter', 'Noto Sans KR', sans-serif;
    background-color: #fbf9f5;
    color: #1b1c1a;
}
.block-container {
    max-width: 1200px;
    padding-top: 1.5rem;
    padding-bottom: 3rem;
}
.hero {
    background: linear-gradient(135deg, #f5e6d3, #efe0cd);
    border: 1px solid #ccc3d8;
    border-left: 9px solid #2E7D32;
    border-radius: 20px;
    padding: 28px 32px;
    margin-bottom: 24px;
    box-shadow: 0px 8px 24px rgba(46, 125, 50, 0.05);
}
.hero .eyebrow {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #2E7D32;
    color: #ffffff;
    border-radius: 999px;
    padding: 4px 12px;
    font-size: 13px;
    font-weight: 700;
    margin-bottom: 12px;
}
.hero h1 {
    margin: 0;
    font-size: clamp(24px, 3vw, 36px);
    line-height: 1.2;
    color: #1b5e20;
    font-weight: 800;
}
.hero p {
    margin: 8px 0 0;
    font-size: 15px;
    color: #4e483b;
    line-height: 1.6;
}
.notice {
    background: #ffffff;
    border: 1px solid #e4e2de;
    border-left: 6px solid #fb8c00;
    border-radius: 12px;
    padding: 14px 16px;
    margin-bottom: 20px;
    font-size: 14px;
    line-height: 1.6;
    color: #4a4455;
}
.section-card {
    background: #ffffff;
    border: 1px solid #e4e2de;
    border-radius: 16px;
    padding: 20px;
    margin-bottom: 18px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.01);
}
div[data-testid="stMetric"] {
    background: #ffffff;
    border: 1px solid #e4e2de;
    border-radius: 14px;
    padding: 12px;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.01);
}
.stButton > button {
    border-radius: 10px !important;
    background: linear-gradient(135deg, #2E7D32, #4CAF50) !important;
    color: #ffffff !important;
    font-weight: 700 !important;
    border: none !important;
    padding: 8px 20px !important;
    min-height: 42px !important;
    box-shadow: 0px 4px 10px rgba(46, 125, 50, 0.2) !important;
    transition: all 0.2s ease-in-out !important;
    width: 100% !important;
}
.stButton > button:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0px 6px 14px rgba(46, 125, 50, 0.3) !important;
}
.stDownloadButton > button {
    border-radius: 10px !important;
    background: #ffffff !important;
    color: #2E7D32 !important;
    font-weight: 700 !important;
    border: 1.5px solid #2E7D32 !important;
    padding: 8px 20px !important;
    min-height: 42px !important;
    width: 100% !important;
}
.stDownloadButton > button:hover {
    background: #e8f5e9 !important;
    color: #1b5e20 !important;
}
</style>
""", unsafe_allow_html=True)

# -----------------------------
# ๋ฐ์ดํ„ฐ ๋™๊ธฐํ™” ๊ธฐ๋™ ์‹œ ์ž๋™ ๋‹ค์šด๋กœ๋“œ
# -----------------------------
if "db_downloaded" not in st.session_state:
    with st.spinner("ํ—ˆ๊น…ํŽ˜์ด์Šค DB ๋ฐ์ดํ„ฐ ๋กœ๋”ฉ ์ค‘..."):
        db_sync.download_all()
    st.session_state["db_downloaded"] = True

# -----------------------------
# ์—‘์…€ ๋ฐ์ดํ„ฐ ํŒŒ์ผ ์ž…์ถœ๋ ฅ ํ—ฌํผ
# -----------------------------
def load_excel_data(relative_path, default_cols):
    local_path = os.path.join(CURRENT_DIR, relative_path)
    os.makedirs(os.path.dirname(local_path), exist_ok=True)
    if os.path.exists(local_path):
        try:
            df = pd.read_excel(local_path)
            # ๊ฒฐ๋ฝ ์ปฌ๋Ÿผ ๋ณด์™„
            for col in default_cols:
                if col not in df.columns:
                    df[col] = ""
            return df
        except Exception:
            pass
    df = pd.DataFrame(columns=default_cols)
    df.to_excel(local_path, index=False)
    return df

def save_excel_data(df, relative_path):
    local_path = os.path.join(CURRENT_DIR, relative_path)
    os.makedirs(os.path.dirname(local_path), exist_ok=True)
    df.to_excel(local_path, index=False)

# -----------------------------
# ๊ธฐ๋Šฅ๋ณ„ ์ปฌ๋Ÿผ ๋ฐ ์˜ต์…˜ ์ƒ์ˆ˜ ์„ ์–ธ
# -----------------------------
CLIENT_COLS = [
    "NO.", "์ˆ˜๊ธ‰์ž์ด๋ฆ„", "๊ฐ€๋ช…ํ‘œ๊ธฐ", "์„ฑ๋ณ„", "์ƒ๋…„์›”์ผ", "์‹ค์งˆ์ƒ์ผ๋‚ ์งœ", "์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰", "์ธ์ •๋ฒˆํ˜ธ",
    "์ธ์ •๊ธฐ๊ฐ„์‹œ์ž‘์ผ", "์ธ์ •๊ธฐ๊ฐ„์ข…๋ฃŒ์ผ", "์ž…์†Œ์ผ", "์ด์šฉ์ƒํƒœ", "์ฃผ์š”์งˆํ™˜", "์ธ์ง€์ƒํƒœ", "์ด๋™์ƒํƒœ",
    "์‹์‚ฌ์ƒํƒœ", "๋ฐฐ๋ณ€/๋ฐฐ๋‡จ์ƒํƒœ", "๋ณดํ˜ธ์ž์ด๋ฆ„", "๋ณดํ˜ธ์ž์—ฐ๋ฝ์ฒ˜", "ํŠน์ด์‚ฌํ•ญ", "๋น„๊ณ ", "๊ธฐ๊ด€์œ ํ˜•", "๊ธฐ๊ด€๋ช…"
]

COUNSELING_COLS = [
    "NO.", "์ˆ˜๊ธ‰์ž์ด๋ฆ„", "๊ฐ€๋ช…ํ‘œ๊ธฐ", "์ƒ๋‹ด์ผ์ž", "์ƒ๋‹ด์ž", "์ƒ๋‹ด๋ถ„๋ฅ˜", "์ƒ๋‹ด์‚ฌ์œ ", "์ƒ๋‹ด๋‚ด์šฉ", "์กฐ์น˜๊ณ„ํš",
    "์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ", "์‚ฌ๋ก€๊ด€๋ฆฌํ•„์š”", "์š•๊ตฌ์‚ฌ์ •ํ•„์š”", "๊ธ‰์—ฌ์ œ๊ณต๊ณ„ํš๋ณ€๊ฒฝํ•„์š”", "๋“ฑ๋ก์ผ์ž"
]

CASE_MANAGEMENT_COLS = [
    "NO.", "์ˆ˜๊ธ‰์ž์ด๋ฆ„", "๊ฐ€๋ช…ํ‘œ๊ธฐ", "ํšŒ์˜์ผ์ž", "์ฐธ์„์ž", "ํšŒ์˜๋ถ„๋ฅ˜", "์‚ฌ๋ก€์„ ์ •์ด์œ ",
    "ํ•ด๊ฒฐ๋ฐฉ์•ˆ(1์ฐจ๊ณ„ํš)", "์‹œํ–‰๊ณผ์ •", "์ข…ํ•ฉ๊ฒฐ๊ณผ(2์ฐจํ‰๊ฐ€)", "๋“ฑ๋ก์ผ์ž"
]

VALID_GENDERS = ["์—ฌ", "๋‚จ", "๊ธฐํƒ€"]
VALID_GRADES = ["1๋“ฑ๊ธ‰", "2๋“ฑ๊ธ‰", "3๋“ฑ๊ธ‰", "4๋“ฑ๊ธ‰", "5๋“ฑ๊ธ‰", "์ธ์ง€์ง€์›๋“ฑ๊ธ‰", "๋“ฑ๊ธ‰์™ธ", "๋ฏธ์ž…๋ ฅ"]
VALID_INST_TYPES = ["๋ฐฉ๋ฌธ์š”์–‘", "๋ฐฉ๋ฌธ๋ชฉ์š•", "๋ฐฉ๋ฌธ๊ฐ„ํ˜ธ", "์ฃผ๊ฐ„๋ณดํ˜ธ", "์š”์–‘์›", "๊ณต๋™์ƒํ™œ๊ฐ€์ •"]
VALID_STATUS = ["์ด์šฉ์ค‘", "์ž…์†Œ์ค‘", "ํ‡ด์†Œ", "์ค‘์ง€", "์‚ฌ๋ง"]

def load_clients():
    df = load_excel_data("data/clients.xlsx", CLIENT_COLS)
    # ๋“ฑ๊ธ‰ ์ˆซ์ž ์ •๊ทœํ™”
    if not df.empty and "์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰" in df.columns:
        df["์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰"] = df["์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰"].apply(lambda x: str(x).strip() + "๋“ฑ๊ธ‰" if str(x).strip() in ["1", "2", "3", "4", "5"] else str(x).strip())
    return df

def load_counseling():
    return load_excel_data("data/counseling_logs.xlsx", COUNSELING_COLS)

def load_case_management():
    return load_excel_data("data/case_management.xlsx", CASE_MANAGEMENT_COLS)

def safe(val, default=""):
    if pd.isna(val) or val is None:
        return default
    return str(val).strip()

def mask_name(name):
    name = safe(name)
    if len(name) >= 3:
        return name[0] + "โ—‹" + name[2:]
    if len(name) == 2:
        return name[0] + "โ—‹"
    return name

# ๐ŸŽ‚ ์ƒ์‹  ์•Œ๋ฆผ ๊ธฐ์ดˆ ๋„๊ตฌ
def get_this_year_birthday(birth_date_str, real_birth_date_str):
    md = ""
    r_val = safe(real_birth_date_str)
    if r_val and re.match(r"^\d{2}-\d{2}$", r_val):
        md = r_val
    if not md:
        b_val = safe(birth_date_str)
        if re.match(r"^\d{4}-\d{2}-\d{2}$", b_val):
            md = b_val[5:10]
    if not md:
        return None
    try:
        m, d = map(int, md.split("-"))
        return date(datetime.now().year, m, d)
    except Exception:
        return None

def display_birthday_alerts(df):
    if df.empty:
        return
    today = date.today()
    this_month = today.month
    today_birthdays = []
    month_birthdays = []
    
    for _, row in df.iterrows():
        name_masked = mask_name(row.get("์ˆ˜๊ธ‰์ž์ด๋ฆ„"))
        bday = get_this_year_birthday(row.get("์ƒ๋…„์›”์ผ"), row.get("์‹ค์งˆ์ƒ์ผ๋‚ ์งœ"))
        if bday:
            if bday.month == today.month and bday.day == today.day:
                today_birthdays.append(f"**{name_masked} ์–ด๋ฅด์‹ **" + (f" (์‹ค์งˆ์ƒ์ผ: {row.get('์‹ค์งˆ์ƒ์ผ๋‚ ์งœ')})" if row.get('์‹ค์งˆ์ƒ์ผ๋‚ ์งœ') else ""))
            elif bday.month == this_month:
                month_birthdays.append(f"**{name_masked} ์–ด๋ฅด์‹ ** ({bday.day}์ผ - " + (f"์‹ค์งˆ: {row.get('์‹ค์งˆ์ƒ์ผ๋‚ ์งœ')}" if row.get('์‹ค์งˆ์ƒ์ผ๋‚ ์งœ') else f"์ƒ๋…„์›”์ผ: {row.get('์ƒ๋…„์›”์ผ')[5:10] if row.get('์ƒ๋…„์›”์ผ') else ''}") + ")")
                
    if today_birthdays or month_birthdays:
        st.markdown(f"### ๐ŸŽ‚ {this_month}์›” ์ƒ์‹  ์•Œ๋ฆผ")
        if today_birthdays:
            st.markdown(f"""
            <div style="background: #fff3e0; border-left: 6px solid #fb8c00; padding: 12px; border-radius: 10px; margin-bottom: 12px; color: #222;">
                ๐ŸŽ‰ <strong>์˜ค๋Š˜ ์ƒ์‹ !</strong> ์˜ค๋Š˜์€ {', '.join(today_birthdays)}์˜ ์ƒ์‹ ์ž…๋‹ˆ๋‹ค. ์ถ•ํ•˜๋“œ๋ฆฝ๋‹ˆ๋‹ค! ๐ŸŽ‚
            </div>
            """, unsafe_allow_html=True)
        if month_birthdays:
            items = "".join([f"<li>{item}</li>" for item in month_birthdays])
            st.markdown(f"""
            <div style="background: #e8f5e9; border-left: 6px solid #43a047; padding: 12px; border-radius: 10px; margin-bottom: 12px; color: #222;">
                ๐ŸŽ <strong>{this_month}์›” ์ƒ์‹  ์–ด๋ฅด์‹  ๋ชฉ๋ก:</strong>
                <ul style="margin: 6px 0 0 16px; padding: 0;">{items}</ul>
            </div>
            """, unsafe_allow_html=True)

# ๐Ÿค– AI ์ „๋ฌธ ์†Œ๊ฒฌ API ์—ฐ๋™๋ถ€
def generate_ai_opinion(system_prompt, user_prompt, client_name, reason, content):
    # API ํ‚ค๋ฅผ ์‚ฌ์ด๋“œ๋ฐ” ํ˜น์€ ํ™˜๊ฒฝ ๋ณ€์ˆ˜์—์„œ ๊ฐ€์ ธ์˜ต๋‹ˆ๋‹ค
    api_key = st.sidebar.text_input("OpenAI API Key (์„ ํƒ)", value=os.environ.get("OPENAI_API_KEY", ""), type="password")
    use_lm_studio = st.sidebar.toggle("LM Studio ์‚ฌ์šฉ (Qwen)", value=False)
    
    if use_lm_studio:
        try:
            ai_client = OpenAI(base_url="http://127.0.0.1:1234/v1", api_key="lm-studio")
            completion = ai_client.chat.completions.create(
                model="qwen2.5-7b-instruct",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                temperature=0.7
            )
            return completion.choices[0].message.content.strip()
        except Exception as e:
            st.sidebar.error(f"LM Studio ์—ฐ๊ฒฐ ์‹คํŒจ: {e}")
            
    if api_key.strip():
        try:
            ai_client = OpenAI(api_key=api_key)
            completion = ai_client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                temperature=0.5
            )
            return completion.choices[0].message.content.strip()
        except Exception as e:
            st.sidebar.error(f"OpenAI API ํ˜ธ์ถœ ์‹คํŒจ: {e}")

    # Fallback Rule-based (๋ฃฐ ๊ธฐ๋ฐ˜ ๋Œ€์ฒด ํ…์ŠคํŠธ)
    return (
        f"1. {client_name} ์–ด๋ฅด์‹ ์˜ ๊ธˆ๋ฒˆ ์ƒ๋‹ด ์‚ฌ์œ ์ธ '{reason}'์— ๋”ฐ๋ผ ์ˆ˜๊ธ‰์ž์˜ ๊ฑด๊ฐ• ๋ฐ ์ƒํ™œ ํŒจํ„ด ๋ณ€ํ™”๋ฅผ ์„ธ๋ฐ€ํ•˜๊ฒŒ ๊ด€์ฐฐํ•˜์˜€์Šต๋‹ˆ๋‹ค.\n"
        f"2. {content[:30]}...์˜ ์ž…๋ ฅ์„ ๋ฐ”ํƒ•์œผ๋กœ ๊ด€์ฐฐํ•œ ๊ฒฐ๊ณผ, ์ผ์ƒ ์ƒํ™œ ์ง€์› ๋ฐ ์‹ ์ฒด ํ™œ๋™ ๊ด€๋ฆฌ์— ์ ๊ทน์ ์ธ ๊ฐœ์ž…์ด ์š”๋ง๋ฉ๋‹ˆ๋‹ค.\n"
        f"3. ์ž‘์„ฑ๋œ ์กฐ์น˜๊ณ„ํš์˜ ์ถฉ์‹คํ•œ ์ดํ–‰ ์—ฌ๋ถ€๋ฅผ ์ •๊ธฐ ๊ฒ€ํ† ํ•˜๊ณ  ์ƒํƒœ ์ด์ƒ ์ง•ํ›„ ํ™•์ธ ์‹œ ์ฆ‰๊ฐ ๋ณดํ˜ธ์ž ๋ฐ ์œ ๊ด€ ์ง์ข…๊ณผ ๊ณต์œ ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค."
    )

# -----------------------------
# ๊ณตํ†ต ๋ ˆ์ด์•„์›ƒ ๊ตฌ์„ฑ
# -----------------------------
st.markdown("""
<div class="hero">
    <div class="eyebrow">BeeCare Core v1.0</div>
    <h1>๐Ÿ BeeCare Core ํ†ตํ•ฉ ์—ฐ๋™ ๋ฌธ์„œ์‹œ์Šคํ…œ</h1>
    <p>์ˆ˜๊ธ‰์ž๋“ฑ๋ก, ์ƒ๋‹ด์ผ์ง€, ์‚ฌ๋ก€๊ด€๋ฆฌ๋ฅผ ํ•˜๋‚˜์˜ ์•ฑ๊ณผ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ํ™˜๊ฒฝ์œผ๋กœ ์™„์ „ ์—ฐ๋™ํ•˜์—ฌ ์‹ค์‹œ๊ฐ„ ๊ณต์œ ๋ฅผ ๋ณด์žฅํ•ฉ๋‹ˆ๋‹ค.</p>
</div>
""", unsafe_allow_html=True)

# ๐Ÿ”„ ์‚ฌ์ด๋“œ๋ฐ” ๋™๊ธฐํ™” ์ œ์–ดํŒ
st.sidebar.subheader("๐Ÿ”„ ์‹ค์‹œ๊ฐ„ ๋™๊ธฐํ™” ์ œ์–ด")
if st.sidebar.button("ํ—ˆ๊น…ํŽ˜์ด์Šค์—์„œ DB ๋‹ค์šด๋กœ๋“œ"):
    with st.spinner("๋‹ค์šด๋กœ๋“œ ์ค‘..."):
        if db_sync.download_all():
            st.sidebar.success("์„ฑ๊ณต์ ์œผ๋กœ ๋‹ค์šด๋กœ๋“œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!")
            st.rerun()
        else:
            st.sidebar.error("๋‹ค์šด๋กœ๋“œ ์‹คํŒจ!")

if st.sidebar.button("ํ—ˆ๊น…ํŽ˜์ด์Šค์— DB ์—…๋กœ๋“œ"):
    with st.spinner("์—…๋กœ๋“œ ์ค‘..."):
        if db_sync.upload_all():
            st.sidebar.success("์„ฑ๊ณต์ ์œผ๋กœ ์—…๋กœ๋“œ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!")
        else:
            st.sidebar.error("์—…๋กœ๋“œ ์‹คํŒจ!")

# -----------------------------
# ํƒญ ์ •์˜ (1์ฐจ ํ†ตํ•ฉ)
# -----------------------------
tab1, tab2, tab3 = st.tabs(["๐Ÿ‘ฅ ์ˆ˜๊ธ‰์ž ๋“ฑ๋ก ยท ๊ด€๋ฆฌ", "๐Ÿ“ ์ƒ๋‹ด์ผ์ง€ ์ž‘์„ฑ", "๐Ÿ“‹ ์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜๋ก"])

# ==========================================
# ํƒญ 1: ์ˆ˜๊ธ‰์ž ๋“ฑ๋ก
# ==========================================
with tab1:
    st.subheader("๐Ÿ‘ฅ ์ˆ˜๊ธ‰์ž ๋“ฑ๋ก ๋ฐ ๊ธฐ์ดˆ ๋ฐ์ดํ„ฐ ๊ด€๋ฆฌ")
    df_clients = load_clients()
    
    display_birthday_alerts(df_clients)
    
    sub_menu = st.radio("์ˆ˜๊ธ‰์ž ๊ด€๋ฆฌ ๋ฉ”๋‰ด", ["์ˆ˜๊ธ‰์ž ์ง์ ‘ ๋“ฑ๋ก", "์—‘์…€ ์ผ๊ด„ ์—…๋กœ๋“œ", "๋“ฑ๋ก๋œ ์ˆ˜๊ธ‰์ž ๋ชฉ๋ก"], horizontal=True)
    
    if sub_menu == "์ˆ˜๊ธ‰์ž ์ง์ ‘ ๋“ฑ๋ก":
        with st.form("client_register_form"):
            st.markdown("##### ๐Ÿ‘ค ๊ธฐ๋ณธ ์ •๋ณด ์ž…๋ ฅ")
            c1, c2, c3 = st.columns(3)
            name = c1.text_input("์ˆ˜๊ธ‰์ž ์ด๋ฆ„")
            gender = c2.selectbox("์„ฑ๋ณ„", VALID_GENDERS)
            birth_date = c3.text_input("์ƒ๋…„์›”์ผ (YYYY-MM-DD)", placeholder="์˜ˆ: 1942-09-20")
            
            c4, c5, c6 = st.columns(3)
            real_birth_date = c4.text_input("์‹ค์งˆ์ƒ์ผ๋‚ ์งœ (MM-DD)", placeholder="์˜ˆ: 09-20 (์Œ๋ ฅ ๋“ฑ)")
            care_grade = c5.selectbox("์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰", VALID_GRADES)
            rec_num = c6.text_input("์ธ์ •๋ฒˆํ˜ธ", placeholder="์ˆซ์ž๋งŒ ์ž…๋ ฅํ•ด๋„ L ์ž๋™ ๊ฒฐํ•ฉ")
            
            c7, c8, c9 = st.columns(3)
            rec_start = c7.text_input("์ธ์ •๊ธฐ๊ฐ„ ์‹œ์ž‘์ผ (YYYY-MM-DD)", placeholder="์˜ˆ: 2025-03-03")
            rec_end = c8.text_input("์ธ์ •๊ธฐ๊ฐ„ ์ข…๋ฃŒ์ผ (YYYY-MM-DD)", placeholder="์˜ˆ: 2027-03-02")
            admission_date = c9.text_input("์ž…์†Œ์ผ/์ด์šฉ์‹œ์ž‘์ผ (YYYY-MM-DD)", placeholder="์˜ˆ: 2025-03-05")
            
            c10, c11, c12 = st.columns(3)
            inst_type = c10.selectbox("๊ธฐ๊ด€ ์œ ํ˜•", VALID_INST_TYPES)
            inst_name = c11.text_input("๊ธฐ๊ด€๋ช…")
            status = c12.selectbox("์ด์šฉ ์ƒํƒœ", VALID_STATUS)
            
            st.markdown("##### ๐Ÿฅ ์–ด๋ฅด์‹  ์ƒํƒœ ๋ฐ ์ผ€์–ด ์กฐ๊ฑด")
            cc1, cc2, cc3 = st.columns(3)
            main_cond = cc1.text_area("์ฃผ์š” ์งˆํ™˜ / ์ƒํƒœ", height=80)
            cog_stat = cc2.text_area("์ธ์ง€ ์ƒํƒœ", height=80)
            mob_stat = cc3.text_area("์ด๋™ ์ƒํƒœ", height=80)
            
            cc4, cc5, cc6 = st.columns(3)
            diet_stat = cc4.text_area("์‹์‚ฌ ์ƒํƒœ", height=80)
            toil_stat = cc5.text_area("๋ฐฐ๋ณ€/๋ฐฐ๋‡จ ์ƒํƒœ", height=80)
            notes = cc6.text_area("ํŠน์ด์‚ฌํ•ญ / ๋ฉ”๋ชจ", height=80)
            
            st.markdown("##### ๐Ÿ‘ฅ ๋ณดํ˜ธ์ž ์ •๋ณด")
            ccc1, ccc2, ccc3 = st.columns(3)
            guard_name = ccc1.text_input("๋ณดํ˜ธ์ž ์„ฑํ•จ")
            guard_phone = ccc2.text_input("๋ณดํ˜ธ์ž ์—ฐ๋ฝ์ฒ˜")
            remarks = ccc3.text_input("๋น„๊ณ ")
            
            submit = st.form_submit_button("์ˆ˜๊ธ‰์ž ์ •๋ณด ์ €์žฅ ๋ฐ ๋™๊ธฐํ™”")
            
            if submit:
                if not name.strip():
                    st.error("์ˆ˜๊ธ‰์ž ์ด๋ฆ„์€ ํ•„์ˆ˜ ์ž…๋ ฅ ํ•ญ๋ชฉ์ž…๋‹ˆ๋‹ค.")
                else:
                    # ์ธ์ •๋ฒˆํ˜ธ L ํฌ๋งท ์ •๋ฆฌ
                    rec_num_clean = rec_num.replace(" ", "").upper()
                    if rec_num_clean and not rec_num_clean.startswith("L"):
                        rec_num_clean = "L" + re.sub(r"[^0-9]", "", rec_num_clean)
                    
                    new_no = len(df_clients) + 1
                    new_row = {
                        "NO.": new_no,
                        "์ˆ˜๊ธ‰์ž์ด๋ฆ„": name.strip(),
                        "๊ฐ€๋ช…ํ‘œ๊ธฐ": mask_name(name),
                        "์„ฑ๋ณ„": gender,
                        "์ƒ๋…„์›”์ผ": birth_date.strip(),
                        "์‹ค์งˆ์ƒ์ผ๋‚ ์งœ": real_birth_date.strip(),
                        "์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰": care_grade,
                        "์ธ์ •๋ฒˆํ˜ธ": rec_num_clean,
                        "์ธ์ •๊ธฐ๊ฐ„์‹œ์ž‘์ผ": rec_start.strip(),
                        "์ธ์ •๊ธฐ๊ฐ„์ข…๋ฃŒ์ผ": rec_end.strip(),
                        "์ž…์†Œ์ผ": admission_date.strip(),
                        "์ด์šฉ์ƒํƒœ": status,
                        "์ฃผ์š”์งˆํ™˜": main_cond.strip(),
                        "์ธ์ง€์ƒํƒœ": cog_stat.strip(),
                        "์ด๋™์ƒํƒœ": mob_stat.strip(),
                        "์‹์‚ฌ์ƒํƒœ": diet_stat.strip(),
                        "๋ฐฐ๋ณ€/๋ฐฐ๋‡จ์ƒํƒœ": toil_stat.strip(),
                        "๋ณดํ˜ธ์ž์ด๋ฆ„": guard_name.strip(),
                        "๋ณดํ˜ธ์ž์—ฐ๋ฝ์ฒ˜": guard_phone.strip(),
                        "ํŠน์ด์‚ฌํ•ญ": notes.strip(),
                        "๋น„๊ณ ": remarks.strip(),
                        "๊ธฐ๊ด€์œ ํ˜•": inst_type,
                        "๊ธฐ๊ด€๋ช…": inst_name.strip()
                    }
                    df_clients = pd.concat([df_clients, pd.DataFrame([new_row])], ignore_index=True)
                    save_excel_data(df_clients, "data/clients.xlsx")
                    db_sync.upload_all()
                    st.success(f"{name} ์–ด๋ฅด์‹ ์˜ ์ •๋ณด๊ฐ€ ๋“ฑ๋ก ๋ฐ ๋™๊ธฐํ™” ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!")
                    st.rerun()

    elif sub_menu == "์—‘์…€ ์ผ๊ด„ ์—…๋กœ๋“œ":
        st.info("๊ธฐ์กด์— ์ œ๊ณต๋œ ์ˆ˜๊ธ‰์ž ๋“ฑ๋ก ์–‘์‹๊ณผ ๋™์ผํ•œ ๊ตฌ์กฐ์˜ ์—‘์…€ ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด ์ฃผ์„ธ์š”.")
        uploaded_file = st.file_uploader("์ˆ˜๊ธ‰์ž ์—‘์…€ ํŒŒ์ผ ์„ ํƒ", type=["xlsx"])
        overwrite = st.checkbox("์ค‘๋ณต ์ด๋ฆ„์ด ์žˆ์„ ๊ฒฝ์šฐ ๊ธฐ์กด ๋ฐ์ดํ„ฐ ๋ฎ์–ด์“ฐ๊ธฐ", value=True)
        
        if uploaded_file:
            try:
                uploaded_df = pd.read_excel(uploaded_file)
                # ์ •๊ทœํ™” ๋ฐ ๋ฐ”์ธ๋”ฉ
                st.dataframe(uploaded_df.head(3), use_container_width=True)
                if st.button("๋ฐ์ดํ„ฐ ์—…๋กœ๋“œ ์‹คํ–‰"):
                    # ๊ธฐ์กด ๋ฐ์ดํ„ฐ์— ๊ฒฐํ•ฉ ๋กœ์ง ๊ตฌํ˜„
                    for _, row in uploaded_df.iterrows():
                        u_name = safe(row.get("์ˆ˜๊ธ‰์ž์ด๋ฆ„"))
                        if not u_name:
                            continue
                        
                        # ๋“ฑ๊ธ‰ ์ •๊ทœํ™”
                        grade_val = safe(row.get("์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰"))
                        if grade_val in ["1", "2", "3", "4", "5"]:
                            grade_val += "๋“ฑ๊ธ‰"
                        if grade_val not in VALID_GRADES:
                            grade_val = "๋ฏธ์ž…๋ ฅ"
                            
                        # ์ธ์ •๋ฒˆํ˜ธ L ์ •๊ทœํ™”
                        rec_raw = safe(row.get("์ธ์ •๋ฒˆํ˜ธ")).upper()
                        if rec_raw and not rec_raw.startswith("L"):
                            rec_raw = "L" + re.sub(r"[^0-9]", "", rec_raw)

                        # ์ค‘๋ณต ์—ฌ๋ถ€ ํ™•์ธ
                        duplicate_mask = df_clients["์ˆ˜๊ธ‰์ž์ด๋ฆ„"] == u_name
                        
                        row_data = {
                            "NO.": len(df_clients) + 1 if not duplicate_mask.any() else df_clients.loc[duplicate_mask, "NO."].values[0],
                            "์ˆ˜๊ธ‰์ž์ด๋ฆ„": u_name,
                            "๊ฐ€๋ช…ํ‘œ๊ธฐ": mask_name(u_name),
                            "์„ฑ๋ณ„": safe(row.get("์„ฑ๋ณ„")) if safe(row.get("์„ฑ๋ณ„")) in VALID_GENDERS else "์—ฌ",
                            "์ƒ๋…„์›”์ผ": safe(row.get("์ƒ๋…„์›”์ผ")),
                            "์‹ค์งˆ์ƒ์ผ๋‚ ์งœ": safe(row.get("์‹ค์งˆ์ƒ์ผ๋‚ ์งœ")),
                            "์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰": grade_val,
                            "์ธ์ •๋ฒˆํ˜ธ": rec_raw,
                            "์ธ์ •๊ธฐ๊ฐ„์‹œ์ž‘์ผ": safe(row.get("์ธ์ •๊ธฐ๊ฐ„์‹œ์ž‘์ผ")),
                            "์ธ์ •๊ธฐ๊ฐ„์ข…๋ฃŒ์ผ": safe(row.get("์ธ์ •๊ธฐ๊ฐ„์ข…๋ฃŒ์ผ")),
                            "์ž…์†Œ์ผ": safe(row.get("์ž…์†Œ์ผ")),
                            "์ด์šฉ์ƒํƒœ": safe(row.get("์ด์šฉ์ƒํƒœ")) if safe(row.get("์ด์šฉ์ƒํƒœ")) in VALID_STATUS else "์ด์šฉ์ค‘",
                            "์ฃผ์š”์งˆํ™˜": safe(row.get("์ฃผ์š”์งˆํ™˜")),
                            "์ธ์ง€์ƒํƒœ": safe(row.get("์ธ์ง€์ƒํƒœ")),
                            "์ด๋™์ƒํƒœ": safe(row.get("์ด๋™์ƒํƒœ")),
                            "์‹์‚ฌ์ƒํƒœ": safe(row.get("์‹์‚ฌ์ƒํƒœ")),
                            "๋ฐฐ๋ณ€/๋ฐฐ๋‡จ์ƒํƒœ": safe(row.get("๋ฐฐ๋ณ€/๋ฐฐ๋‡จ์ƒํƒœ")),
                            "๋ณดํ˜ธ์ž์ด๋ฆ„": safe(row.get("๋ณดํ˜ธ์ž์ด๋ฆ„")),
                            "๋ณดํ˜ธ์ž์—ฐ๋ฝ์ฒ˜": safe(row.get("๋ณดํ˜ธ์ž์—ฐ๋ฝ์ฒ˜")),
                            "ํŠน์ด์‚ฌํ•ญ": safe(row.get("ํŠน์ด์‚ฌํ•ญ")),
                            "๋น„๊ณ ": safe(row.get("๋น„๊ณ ")),
                            "๊ธฐ๊ด€์œ ํ˜•": safe(row.get("๊ธฐ๊ด€์œ ํ˜•")) if safe(row.get("๊ธฐ๊ด€์œ ํ˜•")) in VALID_INST_TYPES else "๋ฐฉ๋ฌธ์š”์–‘",
                            "๊ธฐ๊ด€๋ช…": safe(row.get("๊ธฐ๊ด€๋ช…"))
                        }
                        
                        if duplicate_mask.any() and overwrite:
                            df_clients.loc[duplicate_mask] = list(row_data.values())
                        else:
                            df_clients = pd.concat([df_clients, pd.DataFrame([row_data])], ignore_index=True)
                            
                    # ๋ฒˆํ˜ธ ์žฌ์ •๋ ฌ
                    df_clients["NO."] = range(1, len(df_clients) + 1)
                    save_excel_data(df_clients, "data/clients.xlsx")
                    db_sync.upload_all()
                    st.success("์—‘์…€ ๋ฐ์ดํ„ฐ ์—…๋กœ๋“œ ๋ฐ ์‹ค์‹œ๊ฐ„ ๋™๊ธฐํ™”๊ฐ€ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!")
                    st.rerun()
            except Exception as e:
                st.error(f"์—‘์…€ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {e}")

    elif sub_menu == "๋“ฑ๋ก๋œ ์ˆ˜๊ธ‰์ž ๋ชฉ๋ก":
        if df_clients.empty:
            st.info("๋“ฑ๋ก๋œ ์ˆ˜๊ธ‰์ž ์ •๋ณด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")
        else:
            st.dataframe(df_clients, use_container_width=True, hide_index=True)

# ==========================================
# ํƒญ 2: ์ƒ๋‹ด์ผ์ง€
# ==========================================
with tab2:
    st.subheader("๐Ÿ“ ์—ฐ๋™ ์ƒ๋‹ด์ผ์ง€ ์ž‘์„ฑ")
    df_clients = load_clients()
    df_counseling = load_counseling()
    
    if df_clients.empty:
        st.warning("๋จผ์ € '์ˆ˜๊ธ‰์ž ๋“ฑ๋ก' ํƒญ์—์„œ ์ˆ˜๊ธ‰์ž ๊ธฐ๋ณธ ์ •๋ณด๋ฅผ 1๋ช… ์ด์ƒ ๋“ฑ๋กํ•ด ์ฃผ์„ธ์š”.")
    else:
        st.markdown("##### 1๋‹จ๊ณ„: ์ƒ๋‹ด ๋Œ€์ƒ ์–ด๋ฅด์‹  ์„ ํƒ")
        client_options = df_clients.apply(
            lambda x: f"{x['NO.']}๋ฒˆ - {x['๊ฐ€๋ช…ํ‘œ๊ธฐ']} / {x['์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰']} / {x['๊ธฐ๊ด€์œ ํ˜•']} / {x['์ด์šฉ์ƒํƒœ']}",
            axis=1
        ).tolist()
        
        selected_client_opt = st.selectbox("์ˆ˜๊ธ‰์ž ์„ ํƒ", client_options, key="counsel_client_select")
        selected_no = int(selected_client_opt.split("๋ฒˆ")[0])
        client_row = df_clients[df_clients["NO."] == selected_no].iloc[0]
        
        st.markdown("---")
        st.markdown("##### 2๋‹จ๊ณ„: ์ƒ๋‹ด ์ƒ์„ธ ๋‚ด์šฉ ๊ธฐ๋ก")
        
        with st.form("counseling_form"):
            col_c1, col_c2, col_c3 = st.columns(3)
            c_name = col_c1.text_input("์ˆ˜๊ธ‰์ž ์„ฑ๋ช…", value=safe(client_row["์ˆ˜๊ธ‰์ž์ด๋ฆ„"]), disabled=True)
            c_masked = col_c2.text_input("๊ฐ€๋ช… ํ‘œ๊ธฐ", value=safe(client_row["๊ฐ€๋ช…ํ‘œ๊ธฐ"]), disabled=True)
            c_date = col_c3.date_input("์ƒ๋‹ด์ผ์ž", value=date.today())
            
            col_c4, col_c5 = st.columns(2)
            c_writer = col_c4.text_input("์ƒ๋‹ด์ž", value="์‚ฌํšŒ๋ณต์ง€์‚ฌ")
            c_type = col_c5.selectbox("์ƒ๋‹ด๋ถ„๋ฅ˜", ["์ˆ˜๊ธ‰์ž์ƒ๋‹ด", "๋ณดํ˜ธ์ž์ƒ๋‹ด", "์ข…์‚ฌ์ž์ƒ๋‹ด", "๊ธฐํƒ€์ƒ๋‹ด"])
            
            c_reason = st.selectbox("์ƒ๋‹ด์‚ฌ์œ ", [
                "์ •๊ธฐ์ƒ๋‹ด", "์ƒํƒœ๋ณ€ํ™”์— ๋”ฐ๋ฅธ ์ƒ๋‹ด", "์ˆ˜๊ธ‰์ž ์š”์ฒญ", "๋ณดํ˜ธ์ž ์š”์ฒญ", "์š”์–‘๋ณดํ˜ธ์‚ฌ ๊ฑด์˜", "์‘๊ธ‰์กฐ์น˜ ํ”ผ๋“œ๋ฐฑ"
            ])
            
            c_content = st.text_area("์ƒ๋‹ด๋‚ด์šฉ", placeholder="์ƒ๋‹ดํ•œ ํ•ต์‹ฌ ๋‚ด์šฉ์„ ์œกํ•˜์›์น™์— ์˜๊ฑฐํ•ด ๊ธฐ๋กํ•ด ์ฃผ์„ธ์š”.", height=120)
            c_plan = st.text_area("์กฐ์น˜๊ณ„ํš", placeholder="์ƒ๋‹ด ์ดํ›„ ์–ด๋ฅด์‹ ์—๊ฒŒ ์ œ๊ณต๋  ์กฐ์น˜๋‚˜ ์กฐ์œจ์‚ฌํ•ญ์„ ์ ์–ด์ฃผ์„ธ์š”.", height=80)
            c_needs = st.text_area("์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ", placeholder="์ถ”๊ฐ€๋กœ ์ „๋‹ฌ๋ฐ›์€ ์„œ๋น„์Šค ์š”๊ตฌ๋‚˜ ๋ณดํ˜ธ์ž์˜ ๊ฐœ์„  ์š”์ฒญ ๋“ฑ์„ ์ƒ์„ธํžˆ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.", height=80)
            
            st.markdown("##### โš ๏ธ ํ›„์† ์—…๋ฌด ์—ฐ๋™ ์ง€์ •")
            st.info("์ƒ๋‹ด ๊ฒฐ๊ณผ์— ๋”ฐ๋ผ ์—ฐ๋™ ์ฒ˜๋ฆฌ๊ฐ€ ํ•„์š”ํ•œ ์—…๋ฌด๋ฅผ ์ฒดํฌํ•ด ์ฃผ์„ธ์š”. ํƒญ 3(์‚ฌ๋ก€๊ด€๋ฆฌ)์€ '์‚ฌ๋ก€๊ด€๋ฆฌํ•„์š”'๊ฐ€ ํ™œ์„ฑํ™”๋œ ์–ด๋ฅด์‹ ๋งŒ ์—ฐ๋™๋ฉ๋‹ˆ๋‹ค.")
            col_cb1, col_cb2, col_cb3 = st.columns(3)
            need_case = col_cb1.checkbox("์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜ ํšŒ๋ถ€ ํ•„์š”", value=False)
            need_needs = col_cb2.checkbox("์š•๊ตฌ์‚ฌ์ • ์žฌํ‰๊ฐ€ ํ•„์š”", value=False)
            need_careplan = col_cb3.checkbox("๊ธ‰์—ฌ์ œ๊ณต๊ณ„ํš ๋ณ€๊ฒฝ/์žฌ์ž‘์„ฑ ํ•„์š”", value=False)
            
            st.markdown("##### ๐Ÿค– AI ์†Œ๊ฒฌ ์ƒ์„ฑ")
            st.caption("์ž‘์„ฑ๋œ ๋‚ด์šฉ์„ ๋ฐ”ํƒ•์œผ๋กœ AI๊ฐ€ ์ „๋ฌธ์ ์ธ ์š”์•ฝ์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. (์ž„์˜์˜ ์ฆ์ƒ/์ƒํƒœ๋Š” ์ง€์–ด๋‚ด์ง€ ์•Š์Šต๋‹ˆ๋‹ค)")
            
            ai_opinion = ""
            if st.form_submit_button("๐Ÿค– AI ์ดํ‰ ์ž„์‹œ ์ƒ์„ฑ"):
                if not c_content.strip():
                    st.error("์ƒ๋‹ด๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์•ผ AI ์ดํ‰์„ ๊ตฌ์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
                else:
                    sys_prompt = (
                        "๋‹น์‹ ์€ ์žฅ๊ธฐ์š”์–‘๊ธฐ๊ด€ ํ‰๊ฐ€์™€ ์ƒ๋‹ด๊ธฐ๋ก ์ž‘์„ฑ์— ์ˆ™๋ จ๋œ 20๋…„ ๊ฒฝ๋ ฅ์˜ ์‚ฌํšŒ๋ณต์ง€์‚ฌ์ž…๋‹ˆ๋‹ค. "
                        "ํ‰๊ฐ€ ๊ธฐ์ค€์— ๋ถ€ํ•ฉํ•˜๊ฒŒ ํ•ต์‹ฌ์ด ์ผ๋ชฉ์š”์—ฐํ•˜๊ณ  ๋ช…๋ฃŒํ•œ ์ข…ํ•ฉ์†Œ๊ฒฌ์œผ๋กœ ์ •๋ฆฌํ•ด ์ฃผ์‹ญ์‹œ์˜ค."
                    )
                    user_prompt = f"""
                    [์ˆ˜๊ธ‰์ž ์ •๋ณด]
                    ์ด๋ฆ„: {c_name} (๊ฐ€๋ช…: {c_masked})
                    ์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰: {safe(client_row["์žฅ๊ธฐ์š”์–‘๋“ฑ๊ธ‰"])}
                    
                    [์ƒ๋‹ด ๊ธฐ๋ก]
                    ์ƒ๋‹ด์‚ฌ์œ : {c_reason}
                    ์ƒ๋‹ด๋‚ด์šฉ: {c_content}
                    ์กฐ์น˜๊ณ„ํš: {c_plan}
                    ์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ: {c_needs}
                    
                    [์ฃผ์˜์‚ฌํ•ญ/์ œ์•ฝ]
                    - ์ƒ๋‹ด ๋‚ด์šฉ๊ณผ ์กฐ์น˜ ๊ณ„ํš์— ๊ธฐ์žฌ๋˜์ง€ ์•Š์€ ์‚ฌ์‹ค(์˜ˆ: ๋‚™์ƒ ํ”์ , ์š•์ฐฝ ๋ฐœ์ƒ, ์นจํ•ด ํ–‰๋™, ๊ธฐ์ €๊ท€ ์ –์Œ ๋“ฑ)์„ AI๊ฐ€ ๋…๋‹จ์ ์œผ๋กœ ์ง€์–ด๋‚ด๊ฑฐ๋‚˜ ์ถ”์ •ํ•˜์—ฌ ๊ธฐ์ˆ ํ•˜์ง€ ๋งˆ์‹ญ์‹œ์˜ค.
                    - ์˜ค์ง ์ž…๋ ฅ๋œ ์ •๋ณด๋งŒ์„ ๋ฐ”ํƒ•์œผ๋กœ ์‚ฌํšŒ๋ณต์ง€์‚ฌ ์ข…ํ•ฉ ์†Œ๊ฒฌ ํ˜•์‹์˜ ๋ฌธ์žฅ๋“ค๋กœ 1., 2., 3. ๋ฒˆํ˜ธ ํ˜•ํƒœ๋กœ ์ •๋ฆฌํ•ด์ฃผ์‹ญ์‹œ์˜ค.
                    """
                    ai_opinion = generate_ai_opinion(sys_prompt, user_prompt, c_name, c_reason, c_content)
                    st.session_state["temp_ai_counsel"] = ai_opinion
            
            final_opinion = st.text_area("์ข…ํ•ฉ์†Œ๊ฒฌ (์ง์ ‘ ๋ณด์™„ ๊ฐ€๋Šฅ)", value=st.session_state.get("temp_ai_counsel", ""), height=120)
            
            save_counsel = st.form_submit_button("๐Ÿ“ ์ƒ๋‹ด์ผ์ง€ ์ €์žฅ ๋ฐ ํ—ˆ๊น…ํŽ˜์ด์Šค ์—ฐ๋™")
            
            if save_counsel:
                if not c_content.strip():
                    st.error("์ƒ๋‹ด๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.")
                else:
                    new_no = len(df_counseling) + 1
                    new_row = {
                        "NO.": new_no,
                        "์ˆ˜๊ธ‰์ž์ด๋ฆ„": c_name,
                        "๊ฐ€๋ช…ํ‘œ๊ธฐ": c_masked,
                        "์ƒ๋‹ด์ผ์ž": str(c_date),
                        "์ƒ๋‹ด์ž": c_writer.strip(),
                        "์ƒ๋‹ด๋ถ„๋ฅ˜": c_type,
                        "์ƒ๋‹ด์‚ฌ์œ ": c_reason,
                        "์ƒ๋‹ด๋‚ด์šฉ": c_content.strip(),
                        "์กฐ์น˜๊ณ„ํš": c_plan.strip() if c_plan.strip() else final_opinion.strip(),
                        "์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ": c_needs.strip(),
                        "์‚ฌ๋ก€๊ด€๋ฆฌํ•„์š”": "True" if need_case else "False",
                        "์š•๊ตฌ์‚ฌ์ •ํ•„์š”": "True" if need_needs else "False",
                        "๊ธ‰์—ฌ์ œ๊ณต๊ณ„ํš๋ณ€๊ฒฝํ•„์š”": "True" if need_careplan else "False",
                        "๋“ฑ๋ก์ผ์ž": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    }
                    df_counseling = pd.concat([df_counseling, pd.DataFrame([new_row])], ignore_index=True)
                    save_excel_data(df_counseling, "data/counseling_logs.xlsx")
                    db_sync.upload_all()
                    
                    # ์„ธ์…˜ ํ…œํ”Œ๋ฆฟ ๋น„์šฐ๊ธฐ
                    if "temp_ai_counsel" in st.session_state:
                        del st.session_state["temp_ai_counsel"]
                        
                    st.success("์ƒ๋‹ด์ผ์ง€ ์ €์žฅ์ด ์™„๋ฃŒ๋˜์—ˆ์œผ๋ฉฐ ์‹ค์‹œ๊ฐ„ ์—…๋กœ๋“œ ๋™๊ธฐํ™”๊ฐ€ ๋๋‚ฌ์Šต๋‹ˆ๋‹ค!")
                    st.rerun()

        st.markdown("---")
        st.markdown("##### ๐Ÿ“‚ ๋“ฑ๋ก๋œ ์ƒ๋‹ด์ผ์ง€ ๋ชฉ๋ก")
        if df_counseling.empty:
            st.info("์ž‘์„ฑ๋œ ์ƒ๋‹ด์ผ์ง€ ๋‚ด์—ญ์ด ์—†์Šต๋‹ˆ๋‹ค.")
        else:
            st.dataframe(df_counseling, use_container_width=True, hide_index=True)

# ==========================================
# ํƒญ 3: ์‚ฌ๋ก€๊ด€๋ฆฌ
# ==========================================
with tab3:
    st.subheader("๐Ÿ“‹ ์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜๋ก ์ž‘์„ฑ ๋ฐ ์—ฐ๋™ ๊ด€๋ฆฌ")
    df_counseling = load_counseling()
    df_case = load_case_management()
    
    # โš ๏ธ ์—ฐ๋™ ๊ทœ์น™ ํ•„ํ„ฐ๋ง
    # ์ƒ๋‹ด์ผ์ง€์—์„œ ์‚ฌ๋ก€๊ด€๋ฆฌํ•„์š” == True ์ด๊ฑฐ๋‚˜ ์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ์— "์‚ฌ๋ก€๊ด€๋ฆฌ" ๋‹จ์–ด๊ฐ€ ํฌํ•จ๋œ ๊ฒƒ๋งŒ ์ถ”์ถœ
    qualified_clients = []
    if not df_counseling.empty:
        # ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ์•ˆ์ „ํ•˜๊ฒŒ ํ•„ํ„ฐ๋ง
        df_counseling["์‚ฌ๋ก€๊ด€๋ฆฌํ•„์š”"] = df_counseling["์‚ฌ๋ก€๊ด€๋ฆฌํ•„์š”"].astype(str)
        df_counseling["์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ"] = df_counseling["์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ"].fillna("")
        
        filtered_df = df_counseling[
            (df_counseling["์‚ฌ๋ก€๊ด€๋ฆฌํ•„์š”"] == "True") | 
            (df_counseling["์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ"].str.contains("์‚ฌ๋ก€๊ด€๋ฆฌ", case=False))
        ]
        
        if not filtered_df.empty:
            qualified_clients = filtered_df["์ˆ˜๊ธ‰์ž์ด๋ฆ„"].unique().tolist()
            
    if not qualified_clients:
        st.warning("ํ˜„์žฌ ์ƒ๋‹ด์ผ์ง€์—์„œ '์‚ฌ๋ก€๊ด€๋ฆฌ ํ•„์š”'๋กœ ์„ ๋ณ„๋˜๊ฑฐ๋‚˜ '์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ'์— '์‚ฌ๋ก€๊ด€๋ฆฌ'๊ฐ€ ์ง€์ •๋œ ์—ฐ๋™ ๋Œ€์ƒ ์–ด๋ฅด์‹ ์ด ์—†์Šต๋‹ˆ๋‹ค.")
        st.info("์ƒ๋‹ด์ผ์ง€ ์ž‘์„ฑ ์‹œ ํ›„์† ์—…๋ฌด ์—ฐ๋™์—์„œ '์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜ ํšŒ๋ถ€ ํ•„์š”'๋ฅผ ์ฒดํฌํ•˜์‹œ๋ฉด ์ด๊ณณ์— ์ž๋™์œผ๋กœ ๋“ฑ๋ก๋ฉ๋‹ˆ๋‹ค.")
    else:
        st.markdown("##### ๐Ÿ”— ์ƒ๋‹ด ์—ฐ๋™ ์‚ฌ๋ก€๊ด€๋ฆฌ ๋Œ€์ƒ์ž ์„ ํƒ")
        selected_case_name = st.selectbox("์‚ฌ๋ก€๊ด€๋ฆฌ ๋Œ€์ƒ ์–ด๋ฅด์‹  ์„ ํƒ", qualified_clients, key="case_client_select")
        
        # ํ•ด๋‹น ์–ด๋ฅด์‹ ์˜ ์ตœ๊ทผ ์—ฐ๋™ ์ƒ๋‹ด ๋‚ด์—ญ ์š”์•ฝ ๋…ธ์ถœ
        ref_counsel_logs = df_counseling[df_counseling["์ˆ˜๊ธ‰์ž์ด๋ฆ„"] == selected_case_name].sort_values(by="์ƒ๋‹ด์ผ์ž", ascending=False)
        latest_counsel = ref_counsel_logs.iloc[0]
        
        st.markdown(f"""
        <div style="background: #e1f5fe; border-left: 6px solid #03a9f4; padding: 12px; border-radius: 10px; margin-bottom: 12px; color: #222;">
            ๐Ÿ“ <strong>์—ฐ๋™๋œ ์ตœ๊ทผ ์ƒ๋‹ด ์ •๋ณด ({latest_counsel['์ƒ๋‹ด์ผ์ž']}):</strong><br>
            โ€ข <strong>์ƒ๋‹ด์‚ฌ์œ :</strong> {latest_counsel['์ƒ๋‹ด์‚ฌ์œ ']}<br>
            โ€ข <strong>์ƒ๋‹ด๋‚ด์šฉ:</strong> {latest_counsel['์ƒ๋‹ด๋‚ด์šฉ']}<br>
            โ€ข <strong>์ถ”๊ฐ€์š•๊ตฌ/์š”์ฒญ:</strong> {latest_counsel['์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ']}
        </div>
        """, unsafe_allow_html=True)
        
        with st.form("case_management_form"):
            col_m1, col_m2 = st.columns(2)
            m_name = col_m1.text_input("์ˆ˜๊ธ‰์ž ์„ฑ๋ช…", value=selected_case_name, disabled=True)
            m_masked = col_m2.text_input("๊ฐ€๋ช… ํ‘œ๊ธฐ", value=safe(latest_counsel["๊ฐ€๋ช…ํ‘œ๊ธฐ"]), disabled=True)
            
            col_m3, col_m4, col_m5 = st.columns(3)
            m_date = col_m3.date_input("ํšŒ์˜ ์ผ์ž", value=date.today())
            m_participants = col_m4.text_input("์ฐธ์„์ž", value="์‹œ์„ค์žฅ, ์‚ฌํšŒ๋ณต์ง€์‚ฌ, ๊ฐ„ํ˜ธ์กฐ๋ฌด์‚ฌ, ์š”์–‘๋ณดํ˜ธ์‚ฌ")
            m_type = col_m5.selectbox("ํšŒ์˜ ๊ตฌ๋ถ„", ["์ •๊ธฐ ์‚ฌ๋ก€ํšŒ์˜", "์‘๊ธ‰ ์‚ฌ๋ก€ํšŒ์˜", "์ˆ˜์‹œ ์‚ฌ๋ก€ํšŒ์˜"])
            
            m_reason = st.text_area("์‚ฌ๋ก€ ์„ ์ • ์ด์œ ", value=f"์ƒ๋‹ด๊ธฐ๋ก ์—ฐ๋™์— ์˜๊ฑฐ, ์ƒ๋‹ด ์‚ฌ์œ  '{latest_counsel['์ƒ๋‹ด์‚ฌ์œ ']}' ๋ฐ ์ถ”๊ฐ€ ์š”์ฒญ '{latest_counsel['์ถ”๊ฐ€์š•๊ตฌ์š”์ฒญ์‚ฌํ•ญ']}' ํ•ด๊ฒฐ์„ ์œ„ํ•œ ์กฐ์œจ์ด ์‹œ๊ธ‰ํ•˜์—ฌ ์‚ฌ๋ก€ํšŒ์˜ ๋Œ€์ƒ์ž๋กœ ์„ ์ •ํ•จ.", height=70)
            
            st.markdown("##### ๐Ÿ“ ํšŒ์˜ ํ•ต์‹ฌ ๊ธฐ๋ก")
            m_first_plan = st.text_area("ํ•ด๊ฒฐ ๋ฐฉ์•ˆ ๋ฐ 1์ฐจ ๊ณ„ํš", placeholder="ํšŒ์˜๋ฅผ ํ†ตํ•ด ๊ฒฐ์ •๋œ ๊ตฌ์ฒด์ ์ธ ์‹คํ–‰ ๊ณ„ํš์„ ์ž‘์„ฑํ•ด ์ฃผ์„ธ์š”.", height=90)
            m_process = st.text_area("์‹œํ–‰ ๊ณผ์ • ๊ธฐ๋ก", placeholder="ํ•ด๊ฒฐ ๋ฐฉ์•ˆ ์ ์šฉ ํ›„ ์‹คํ–‰ ๊ณผ์ •์ƒ์˜ ํ”ผ๋“œ๋ฐฑ์ด๋‚˜ ํŠน์ด์‚ฌํ•ญ์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.", height=90)
            m_result = st.text_area("์ข…ํ•ฉ ๊ฒฐ๊ณผ ๋ฐ 2์ฐจ ํ‰๊ฐ€", placeholder="ํšŒ์˜ ๊ฒฐ๊ณผ ํ‰๊ฐ€ ๋ฐ ํ–ฅํ›„ ๋ฐ˜์˜ํ•  ๊ธ‰์—ฌ ๋‚ด์šฉ์„ ์ž‘์„ฑํ•ด ์ฃผ์„ธ์š”.", height=90)
            
            st.markdown("##### ๐Ÿค– AI ์ „๋ฌธ ์†Œ๊ฒฌ ์ƒ์„ฑ")
            st.caption("์ž…๋ ฅ๋œ ๊ตฌ์ฒด์ ์ธ ๋‚ด์šฉ์—๋งŒ ํ•œ์ •ํ•˜์—ฌ AI๊ฐ€ ์‚ฌ๋ก€ํšŒ์˜ ์ข…ํ•ฉ ์˜๊ฒฌ์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.")
            
            ai_case_opinion = ""
            if st.form_submit_button("๐Ÿค– AI ์ข…ํ•ฉ ์˜๊ฒฌ ์ž„์‹œ ์ƒ์„ฑ"):
                if not m_first_plan.strip():
                    st.error("1์ฐจ ๊ณ„ํš ๋ฐ ํ•ด๊ฒฐ๋ฐฉ์•ˆ์„ ์ž…๋ ฅํ•ด์•ผ ์ข…ํ•ฉ ์†Œ๊ฒฌ ์ž‘์„ฑ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.")
                else:
                    sys_prompt = (
                        "๋‹น์‹ ์€ ์žฅ๊ธฐ์š”์–‘๊ธฐ๊ด€ ํ‰๊ฐ€์— ์ •ํ†ตํ•œ ๋…ธ์ธ๋ณต์ง€ ์ „๋ฌธ๊ฐ€์ด์ž ์‚ฌํšŒ๋ณต์ง€์‚ฌ์ž…๋‹ˆ๋‹ค. "
                        "์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜๋ก์˜ ๊ฒฐ๊ณผ๋ฅผ ํ‰๊ฐ€ ๊ธฐ์ค€์— ๋ถ€ํ•ฉํ•˜๊ฒŒ ๋ช…๋ฃŒํ•œ ๋ฌธ์žฅ๋“ค๋กœ ์ •๋ฆฌํ•ด ์ฃผ์‹ญ์‹œ์˜ค."
                    )
                    user_prompt = f"""
                    [์ˆ˜๊ธ‰์ž]
                    ์ด๋ฆ„: {m_name} (๊ฐ€๋ช…: {m_masked})
                    
                    [์‚ฌ๋ก€๊ด€๋ฆฌ ๊ธฐ๋ก]
                    ์„ ์ •์ด์œ : {m_reason}
                    ํ•ด๊ฒฐ๋ฐฉ์•ˆ ๋ฐ 1์ฐจ๊ณ„ํš: {m_first_plan}
                    ์‹œํ–‰๊ณผ์ •: {m_process}
                    ์ข…ํ•ฉ๊ฒฐ๊ณผ(2์ฐจํ‰๊ฐ€): {m_result}
                    
                    [์ œ์•ฝ์กฐ๊ฑด]
                    - ์ ˆ๋Œ€๋กœ ์ž…๋ ฅ๋œ ๋‚ด์šฉ ์ด์™ธ์— ๋‹ค๋ฅธ ๋ณ‘์ฆ ์ƒํƒœ๋‚˜ ์‘๊ธ‰ ๋‚™์ƒ ์‚ฌ๊ฑด ๋“ฑ์„ ๊ฑฐ์ง“์œผ๋กœ ์ง€์–ด๋‚ด์ง€ ๋งˆ์‹ญ์‹œ์˜ค.
                    - ์˜ค์ง ์ž…๋ ฅ๋œ ๋ฌธ๋งฅ์— ์˜๊ฑฐํ•˜์—ฌ ์ข…ํ•ฉ์ ์ธ ์‚ฌ๋ก€ํšŒ์˜ ์†Œ๊ฒฌ์„ 1., 2., 3. ๋ฒˆํ˜ธ ํ˜•ํƒœ๋กœ ์ •๋ฆฌํ•ด์ฃผ์‹ญ์‹œ์˜ค.
                    """
                    ai_case_opinion = generate_ai_opinion(sys_prompt, user_prompt, m_name, "์‚ฌ๋ก€ํšŒ์˜", m_first_plan)
                    st.session_state["temp_ai_case"] = ai_case_opinion
                    
            final_case_opinion = st.text_area("์‚ฌ๋ก€ํšŒ์˜ ์ข…ํ•ฉ์˜๊ฒฌ ๋ณด์™„", value=st.session_state.get("temp_ai_case", ""), height=100)
            
            save_case = st.form_submit_button("๐Ÿ“‹ ์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜๋ก ์ €์žฅ ๋ฐ ํ—ˆ๊น…ํŽ˜์ด์Šค ์—ฐ๋™")
            
            if save_case:
                if not m_first_plan.strip():
                    st.error("ํ•ด๊ฒฐ๋ฐฉ์•ˆ(1์ฐจ๊ณ„ํš)์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”.")
                else:
                    new_no = len(df_case) + 1
                    new_row = {
                        "NO.": new_no,
                        "์ˆ˜๊ธ‰์ž์ด๋ฆ„": m_name,
                        "๊ฐ€๋ช…ํ‘œ๊ธฐ": m_masked,
                        "ํšŒ์˜์ผ์ž": str(m_date),
                        "์ฐธ์„์ž": m_participants.strip(),
                        "ํšŒ์˜๋ถ„๋ฅ˜": m_type,
                        "์‚ฌ๋ก€์„ ์ •์ด์œ ": m_reason.strip(),
                        "ํ•ด๊ฒฐ๋ฐฉ์•ˆ(1์ฐจ๊ณ„ํš)": m_first_plan.strip(),
                        "์‹œํ–‰๊ณผ์ •": m_process.strip(),
                        "์ข…ํ•ฉ๊ฒฐ๊ณผ(2์ฐจํ‰๊ฐ€)": m_result.strip() if m_result.strip() else final_case_opinion.strip(),
                        "๋“ฑ๋ก์ผ์ž": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    }
                    df_case = pd.concat([df_case, pd.DataFrame([new_row])], ignore_index=True)
                    save_excel_data(df_case, "data/case_management.xlsx")
                    db_sync.upload_all()
                    
                    if "temp_ai_case" in st.session_state:
                        del st.session_state["temp_ai_case"]
                        
                    st.success("์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜๋ก ์ €์žฅ์ด ์™„๋ฃŒ๋˜์—ˆ์œผ๋ฉฐ ์‹ค์‹œ๊ฐ„ ์—…๋กœ๋“œ ๋™๊ธฐํ™”๊ฐ€ ๋๋‚ฌ์Šต๋‹ˆ๋‹ค!")
                    st.rerun()

        st.markdown("---")
        st.markdown("##### ๐Ÿ“‚ ๋“ฑ๋ก๋œ ์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜๋ก ๋ชฉ๋ก")
        if df_case.empty:
            st.info("์ž‘์„ฑ๋œ ์‚ฌ๋ก€๊ด€๋ฆฌ ํšŒ์˜๋ก ๋‚ด์—ญ์ด ์—†์Šต๋‹ˆ๋‹ค.")
        else:
            st.dataframe(df_case, use_container_width=True, hide_index=True)