File size: 24,456 Bytes
86a8165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
λ…Έμ½”λ”© Python+ β€” μ‚¬νšŒκ³Όν•™ μ—°κ΅¬μžμš© 데이터 뢄석 μ›Ήμ•±
FastAPI backend
"""
import io
import json
import os
import re
import threading
import traceback
import uuid
from datetime import datetime
from pathlib import Path
from typing import Optional

import numpy as np
import pandas as pd
from dotenv import load_dotenv
from fastapi import BackgroundTasks, FastAPI, File, HTTPException, UploadFile
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel

import anthropic
from sandbox import execute_code

load_dotenv()

# ──────────────────────────────────────────────────────────────
# Matplotlib ν•œκΈ€ 폰트 감지 (μ„œλ²„ μ‹œμž‘ μ‹œ 1회 μ‹€ν–‰)
# ──────────────────────────────────────────────────────────────
def _detect_korean_font() -> str:
    """μ‚¬μš© κ°€λŠ₯ν•œ ν•œκΈ€ 폰트 이름을 λ°˜ν™˜. μ—†μœΌλ©΄ DejaVu Sans."""
    try:
        import matplotlib.font_manager as fm
        keywords = ["nanum", "malgun", "gothic", "gulim", "dotum", "batang"]
        for f in fm.fontManager.ttflist:
            if any(k in f.name.lower() for k in keywords):
                return f.name
    except Exception:
        pass
    return "DejaVu Sans"

MATPLOTLIB_FONT = _detect_korean_font()

# ──────────────────────────────────────────────────────────────
# App & directory setup
# ──────────────────────────────────────────────────────────────
app = FastAPI(title="λ…Έμ½”λ”© Python+", version="1.0.0")

BASE_DIR = Path(__file__).parent
UPLOAD_DIR = BASE_DIR / "uploads"
RESULTS_DIR = BASE_DIR / "results"
STATIC_DIR = BASE_DIR / "static"

for d in [UPLOAD_DIR, RESULTS_DIR]:
    d.mkdir(exist_ok=True)

# ──────────────────────────────────────────────────────────────
# In-memory stores (protected by a lock)
# ──────────────────────────────────────────────────────────────
sessions: dict = {}
jobs: dict = {}
_lock = threading.Lock()

# ──────────────────────────────────────────────────────────────
# Claude client (lazy β€” fails gracefully if key missing)
# ──────────────────────────────────────────────────────────────
def get_claude_client() -> anthropic.Anthropic:
    api_key = os.getenv("ANTHROPIC_API_KEY")
    if not api_key:
        raise HTTPException(
            503,
            "ANTHROPIC_API_KEYκ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. .env νŒŒμΌμ„ ν™•μΈν•΄μ£Όμ„Έμš”.",
        )
    return anthropic.Anthropic(api_key=api_key)


# ──────────────────────────────────────────────────────────────
# Request / Response models
# ──────────────────────────────────────────────────────────────
class AnalyzeRequest(BaseModel):
    session_id: str
    query: str
    job_id: Optional[str] = None  # optional follow-up context


# ──────────────────────────────────────────────────────────────
# Data helpers
# ──────────────────────────────────────────────────────────────
def _classify_column(series: pd.Series) -> str:
    if pd.api.types.is_datetime64_any_dtype(series):
        return "λ‚ μ§œν˜•"
    if pd.api.types.is_numeric_dtype(series):
        return "μˆ˜μΉ˜ν˜•"
    n_unique = series.nunique(dropna=True)
    if n_unique <= 20 or (len(series) > 0 and n_unique / len(series) < 0.05):
        return "λ²”μ£Όν˜•"
    return "λ¬Έμžν˜•"


def build_df_info(df: pd.DataFrame) -> dict:
    columns = []
    for col in df.columns:
        col_type = _classify_column(df[col])
        sample_vals = df[col].dropna().head(3).tolist()
        # Make sample JSON-serialisable
        sample_vals = [
            str(v) if not isinstance(v, (int, float, bool)) else v
            for v in sample_vals
        ]
        columns.append(
            {
                "name": col,
                "type": col_type,
                "dtype": str(df[col].dtype),
                "missing": int(df[col].isna().sum()),
                "missing_pct": round(df[col].isna().sum() / max(len(df), 1) * 100, 1),
                "unique": int(df[col].nunique(dropna=True)),
                "sample": sample_vals,
            }
        )
    return {
        "shape": list(df.shape),
        "columns": columns,
        "missing_cols": sum(1 for c in columns if c["missing"] > 0),
    }


def df_to_preview(df: pd.DataFrame) -> list:
    preview = df.head(50).copy()
    for col in preview.columns:
        preview[col] = preview[col].astype(str).replace("nan", "")
    return preview.to_dict("records")


def safe_read_file(file_path: Path, ext: str) -> pd.DataFrame:
    if ext == ".csv":
        for enc in ["utf-8-sig", "utf-8", "cp949", "euc-kr"]:
            try:
                return pd.read_csv(file_path, encoding=enc)
            except UnicodeDecodeError:
                continue
        raise ValueError("CSV 인코딩을 인식할 수 μ—†μŠ΅λ‹ˆλ‹€.")
    return pd.read_excel(file_path)


# ──────────────────────────────────────────────────────────────
# Sample data generator
# ──────────────────────────────────────────────────────────────
def make_sample_df() -> pd.DataFrame:
    rng = np.random.default_rng(42)
    n = 200
    genders = rng.choice(["남", "μ—¬"], n)
    pre = rng.normal(60, 15, n).clip(0, 100).round(1)
    # post slightly higher on average to show a real effect
    post = (pre + rng.normal(8, 10, n)).clip(0, 100).round(1)
    return pd.DataFrame(
        {
            "ID": range(1, n + 1),
            "gender": genders,
            "age": rng.integers(22, 60, n),
            "education": rng.choice(["κ³ μ‘Έ", "λŒ€μ‘Έ", "석사", "박사"], n, p=[0.15, 0.50, 0.25, 0.10]),
            "department": rng.choice(["μΈλ¬Έμ‚¬νšŒ", "이곡계", "예술체윑", "μ˜μ•½"], n),
            "experience_years": rng.integers(0, 25, n),
            "satisfaction_job": rng.integers(1, 6, n),
            "satisfaction_wage": rng.integers(1, 6, n),
            "satisfaction_balance": rng.integers(1, 6, n),
            "satisfaction_overall": rng.integers(1, 6, n),
            "pre_score": pre,
            "post_score": post,
            "stress_level": rng.integers(1, 6, n),
        }
    )


# ──────────────────────────────────────────────────────────────
# Claude prompts
# ──────────────────────────────────────────────────────────────
CODE_SYSTEM_PROMPT = """당신은 μ‚¬νšŒκ³Όν•™ μ—°κ΅¬μžλ₯Ό μœ„ν•œ Python 데이터 뢄석 μ „λ¬Έκ°€μž…λ‹ˆλ‹€.
μ‚¬μš©μžμ˜ μžμ—°μ–΄ μš”μ²­μ„ λ°›μ•„ μ™„μ „νžˆ μ‹€ν–‰ κ°€λŠ₯ν•œ Python 뢄석 μ½”λ“œλ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.

## μ½”λ“œ κ·œμΉ™

1. μ‚¬μš© κ°€λŠ₯ν•œ 라이브러리만 μ‚¬μš©ν•˜μ„Έμš”:
   pandas, numpy, scipy, matplotlib, seaborn, sklearn, statsmodels,
   openpyxl, json, os, warnings, math, re, io, base64

2. μ½”λ“œ μ΅œμƒλ‹¨ (λ°˜λ“œμ‹œ 포함):
   import matplotlib
   matplotlib.use('Agg')
   import matplotlib.pyplot as plt
   import matplotlib.font_manager as fm
   # ν•œκΈ€ 폰트 μ„€μ • (Windows/Linux/Mac μžλ™ 감지)
   _kor_keywords = ['nanum', 'malgun', 'gothic', 'gulim', 'dotum', 'batang']
   _kor_fonts = [f.name for f in fm.fontManager.ttflist
                 if any(k in f.name.lower() for k in _kor_keywords)]
   plt.rcParams['font.family'] = _kor_fonts[0] if _kor_fonts else 'DejaVu Sans'
   plt.rcParams['axes.unicode_minus'] = False

3. 사전 μ •μ˜λœ λ³€μˆ˜ (μˆ˜μ • κΈˆμ§€, κ·ΈλŒ€λ‘œ μ‚¬μš©):
   DATA_PATH   β€” CSV 데이터 파일 경둜
   OUTPUT_DIR  β€” κ²°κ³Ό 파일 μ €μž₯ 디렉토리
   RESULT_FILE β€” κ²°κ³Ό JSON μ €μž₯ 경둜

4. 데이터 λ‘œλ”©: pd.read_csv(DATA_PATH, encoding='utf-8-sig')

5. 뢄석 μ™„λ£Œ ν›„ λ°˜λ“œμ‹œ RESULT_FILE에 JSON μ €μž₯:
   result = {
       "summary": "μˆ˜ν–‰ν•œ 뢄석 ν•œκ΅­μ–΄ μš”μ•½ (2-3λ¬Έμž₯)",
       "preprocessing": ["μ „μ²˜λ¦¬1", "μ „μ²˜λ¦¬2"],
       "method": "μ‚¬μš© 톡계 기법 이름",
       "tables": [{"title": "ν‘œ 제λͺ©", "html": "HTML λ¬Έμžμ—΄"}],
       "charts": ["μ €μž₯ν•œ 차트 파일λͺ… λͺ©λ‘"],
       "interpretation": "λΉ„μ „κ³΅μžλ„ 이해할 수 μžˆλŠ” ν•œκ΅­μ–΄ κ²°κ³Ό 해석 (3-5λ¬Έμž₯, 수치 포함)",
       "packages": ["μ‚¬μš© νŒ¨ν‚€μ§€ λͺ©λ‘"],
       "log": "κ²½κ³ /νŠΉμ΄μ‚¬ν•­ (μ—†μœΌλ©΄ 빈 λ¬Έμžμ—΄)"
   }
   with open(RESULT_FILE, 'w', encoding='utf-8') as f:
       json.dump(result, f, ensure_ascii=False, indent=2)

6. 차트 μ €μž₯:
   plt.savefig(os.path.join(OUTPUT_DIR, 'chart_01.png'), dpi=150, bbox_inches='tight')
   plt.close()

7. HTML ν…Œμ΄λΈ” 생성:
   df.to_html(classes='result-table', index=False, border=0)

8. 전체λ₯Ό try-except둜 감싸고, 였λ₯˜ λ°œμƒ μ‹œμ—λ„ λΆ€λΆ„ κ²°κ³Όλ₯Ό RESULT_FILE에 μ €μž₯ν•˜μ„Έμš”.

9. 뢄석 κ²°κ³Ό Excel μ €μž₯ (선택사항):
   result_df.to_excel(os.path.join(OUTPUT_DIR, 'analysis_result.xlsx'), index=False)

μ½”λ“œλ§Œ λ°˜ν™˜ν•˜μ„Έμš”. ```python λΈ”λ‘μœΌλ‘œ κ°μ‹Έμ„œ λ°˜ν™˜ν•˜μ„Έμš”. μ„€λͺ…은 ν•„μš” μ—†μŠ΅λ‹ˆλ‹€."""


def _extract_code_from_response(text: str) -> str:
    if "```python" in text:
        return text.split("```python")[1].split("```")[0].strip()
    if "```" in text:
        return text.split("```")[1].split("```")[0].strip()
    return text.strip()


def _build_col_info(df_info: dict) -> str:
    lines = []
    for c in df_info["columns"]:
        sample_str = ", ".join(str(s) for s in c["sample"])
        missing_str = f"κ²°μΈ‘ {c['missing']}개" if c["missing"] else "κ²°μΈ‘ μ—†μŒ"
        lines.append(f"  - {c['name']} ({c['type']}, {missing_str}, κ³ μœ κ°’ {c['unique']}개): μƒ˜ν”Œ=[{sample_str}]")
    return "\n".join(lines)


def generate_analysis_code(session_info: dict, query: str, prev_results: Optional[dict] = None) -> str:
    client = get_claude_client()
    df_info = session_info["df_info"]
    col_info = _build_col_info(df_info)

    prev_ctx = ""
    if prev_results:
        prev_ctx = f"\n\n이전 뢄석 κ²°κ³Ό (참고용):\n방법: {prev_results.get('method', '')}\nμš”μ•½: {prev_results.get('summary', '')}"

    user_message = f"""데이터 정보:
- 파일: {session_info['file_name']}
- 크기: {df_info['shape'][0]}ν–‰ Γ— {df_info['shape'][1]}μ—΄
- 결츑치 포함 컬럼: {df_info['missing_cols']}개

컬럼 λͺ©λ‘:
{col_info}
{prev_ctx}

μ‚¬μš©μž μš”μ²­: {query}

μœ„ μš”μ²­μ„ μ²˜λ¦¬ν•˜λŠ” Python μ½”λ“œλ₯Ό μƒμ„±ν•΄μ£Όμ„Έμš”."""

    response = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=4096,
        system=CODE_SYSTEM_PROMPT,
        messages=[{"role": "user", "content": user_message}],
    )
    return _extract_code_from_response(response.content[0].text)


# ──────────────────────────────────────────────────────────────
# Error message translator
# ──────────────────────────────────────────────────────────────
def friendly_error(stderr: str) -> str:
    if "TimeoutExpired" in stderr or "timeout" in stderr.lower():
        return "뢄석 μ‹œκ°„μ΄ μ΄ˆκ³Όλ˜μ—ˆμŠ΅λ‹ˆλ‹€ (μ΅œλŒ€ 120초). 더 κ°„λ‹¨ν•œ 뢄석을 μš”μ²­ν•΄λ³΄μ„Έμš”."
    if "MemoryError" in stderr:
        return "λ©”λͺ¨λ¦¬κ°€ λΆ€μ‘±ν•©λ‹ˆλ‹€. 데이터 크기λ₯Ό μ€„μ΄κ±°λ‚˜ 뢄석 λ²”μœ„λ₯Ό μ’ν˜€μ£Όμ„Έμš”."
    m = re.search(r"KeyError: ['\"](.+?)['\"]", stderr)
    if m:
        return f"'{m.group(1)}' μ»¬λŸΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€. 데이터 λ―Έλ¦¬λ³΄κΈ°μ—μ„œ 컬럼λͺ…을 ν™•μΈν•΄μ£Όμ„Έμš”."
    if "ModuleNotFoundError" in stderr:
        m2 = re.search(r"No module named '(.+?)'", stderr)
        if m2:
            return f"'{m2.group(1)}' 라이브러리λ₯Ό μ‚¬μš©ν•  수 μ—†μŠ΅λ‹ˆλ‹€."
    if "ValueError" in stderr and "convert" in stderr.lower():
        return "μˆ«μžν˜• λ³€ν™˜μ— μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. ν•΄λ‹Ή 컬럼이 μ‹€μ œλ‘œ μˆ«μžν˜•μΈμ§€ ν™•μΈν•΄μ£Όμ„Έμš”."
    if "not enough values" in stderr or "shape" in stderr.lower():
        return "데이터 ꡬ쑰가 뢄석에 μ ν•©ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€. λ‹€λ₯Έ 뢄석 방법을 μ‹œλ„ν•΄λ³΄μ„Έμš”."
    return "뢄석 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μš”μ²­μ„ λ‹€λ₯΄κ²Œ ν‘œν˜„ν•˜κ±°λ‚˜ λ‹€λ₯Έ 뢄석을 μ‹œλ„ν•΄λ³΄μ„Έμš”."


# ──────────────────────────────────────────────────────────────
# Background analysis job
# ──────────────────────────────────────────────────────────────
def _update_job(job_id: str, **kwargs):
    with _lock:
        for k, v in kwargs.items():
            if k == "log_append":
                jobs[job_id].setdefault("log", []).append(v)
            else:
                jobs[job_id][k] = v


def run_analysis_job(job_id: str, session_id: str, query: str, prev_results: Optional[dict]):
    _update_job(job_id, status="generating_code", log_append="뢄석 κ³„νš 수립 쀑…")

    session_info = sessions.get(session_id)
    if not session_info:
        _update_job(job_id, status="error", error="μ„Έμ…˜μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
        return

    job_dir = RESULTS_DIR / job_id
    job_dir.mkdir(exist_ok=True)
    result_file = job_dir / "result.json"

    try:
        # ── Step 1: code generation ────────────────────────────
        _update_job(job_id, log_append="Claudeκ°€ Python μ½”λ“œλ₯Ό 생성 쀑…")
        code = generate_analysis_code(session_info, query, prev_results)
        _update_job(job_id, code=code, status="executing", log_append="μ½”λ“œ 생성 μ™„λ£Œ. μ‹€ν–‰ 쀑…")

        # ── Step 2: sandbox execution ──────────────────────────
        exec_result = execute_code(
            code=code,
            data_path=session_info["csv_path"],
            output_dir=str(job_dir),
            result_file=str(result_file),
        )

        if exec_result["success"] and result_file.exists():
            with open(result_file, "r", encoding="utf-8") as f:
                analysis_results = json.load(f)

            # Collect downloadable files
            files = []
            for p in sorted(job_dir.iterdir()):
                if p.name != "result.json":
                    files.append(p.name)

            _update_job(
                job_id,
                status="completed",
                results=analysis_results,
                files=files,
                completed_at=datetime.now().isoformat(),
                log_append="뢄석 μ™„λ£Œ!",
            )
            with _lock:
                sessions[session_id]["analyses"].append(
                    {"job_id": job_id, "query": query, "completed_at": datetime.now().isoformat()}
                )

        elif not result_file.exists():
            stderr = exec_result.get("stderr", "")
            _update_job(
                job_id,
                status="error",
                error=friendly_error(stderr) if stderr else "κ²°κ³Ό 파일이 μƒμ„±λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€.",
                stderr=exec_result.get("stderr", ""),
                log_append="였λ₯˜: κ²°κ³Ό 파일 μ—†μŒ",
            )
        else:
            stderr = exec_result.get("stderr", "")
            _update_job(
                job_id,
                status="error",
                error=friendly_error(stderr),
                stderr=stderr,
                log_append=f"μ‹€ν–‰ 였λ₯˜: {stderr[:200]}",
            )

    except anthropic.APIError as exc:
        _update_job(job_id, status="error", error=f"Claude API 였λ₯˜: {exc}")
    except Exception:
        _update_job(
            job_id,
            status="error",
            error="λ‚΄λΆ€ 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. μž μ‹œ ν›„ λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”.",
            log_append=traceback.format_exc(),
        )


# ──────────────────────────────────────────────────────────────
# Routes
# ──────────────────────────────────────────────────────────────

@app.get("/")
async def root():
    return FileResponse(str(STATIC_DIR / "index.html"))


@app.get("/api/health")
async def health():
    api_key_set = bool(os.getenv("ANTHROPIC_API_KEY"))
    return {"status": "ok", "api_key_configured": api_key_set}


@app.post("/api/upload")
async def upload_file(file: UploadFile = File(...)):
    filename = file.filename or "upload"
    ext = Path(filename).suffix.lower()
    if ext not in {".xlsx", ".xls", ".csv"}:
        raise HTTPException(400, "μ§€μ›ν•˜μ§€ μ•ŠλŠ” 파일 ν˜•μ‹μž…λ‹ˆλ‹€. .xlsx, .xls, .csv 파일만 μ§€μ›ν•©λ‹ˆλ‹€.")

    content = await file.read()
    size_mb = len(content) / (1024 * 1024)
    if size_mb > 50:
        raise HTTPException(400, f"파일 크기가 λ„ˆλ¬΄ ν½λ‹ˆλ‹€ ({size_mb:.1f} MB). μ΅œλŒ€ 50 MBκΉŒμ§€ μ§€μ›ν•©λ‹ˆλ‹€.")

    session_id = str(uuid.uuid4())
    file_path = UPLOAD_DIR / f"{session_id}{ext}"
    file_path.write_bytes(content)

    try:
        df = safe_read_file(file_path, ext)
    except Exception as exc:
        file_path.unlink(missing_ok=True)
        raise HTTPException(400, f"νŒŒμΌμ„ 읽을 수 μ—†μŠ΅λ‹ˆλ‹€: {exc}")

    if df.empty:
        file_path.unlink(missing_ok=True)
        raise HTTPException(400, "파일이 λΉ„μ–΄ μžˆμŠ΅λ‹ˆλ‹€.")

    csv_path = UPLOAD_DIR / f"{session_id}.csv"
    df.to_csv(csv_path, index=False, encoding="utf-8-sig")

    df_info = build_df_info(df)
    preview = df_to_preview(df)

    with _lock:
        sessions[session_id] = {
            "session_id": session_id,
            "file_name": filename,
            "file_path": str(file_path),
            "csv_path": str(csv_path),
            "size_mb": round(size_mb, 2),
            "created_at": datetime.now().isoformat(),
            "df_info": df_info,
            "preview": preview,
            "analyses": [],
        }

    return {
        "session_id": session_id,
        "file_name": filename,
        "rows": df_info["shape"][0],
        "cols": df_info["shape"][1],
        "size_mb": round(size_mb, 2),
    }


@app.get("/api/sample/load")
async def load_sample():
    """Create a session from built-in sample data."""
    df = make_sample_df()
    session_id = str(uuid.uuid4())
    csv_path = UPLOAD_DIR / f"{session_id}.csv"
    df.to_csv(csv_path, index=False, encoding="utf-8-sig")

    df_info = build_df_info(df)
    preview = df_to_preview(df)

    with _lock:
        sessions[session_id] = {
            "session_id": session_id,
            "file_name": "sample_survey_data.csv",
            "file_path": str(csv_path),
            "csv_path": str(csv_path),
            "size_mb": round(csv_path.stat().st_size / 1024 / 1024, 3),
            "created_at": datetime.now().isoformat(),
            "df_info": df_info,
            "preview": preview,
            "analyses": [],
        }

    return {
        "session_id": session_id,
        "file_name": "sample_survey_data.csv",
        "rows": df_info["shape"][0],
        "cols": df_info["shape"][1],
        "size_mb": round(csv_path.stat().st_size / 1024 / 1024, 3),
    }


@app.get("/api/preview/{session_id}")
async def get_preview(session_id: str):
    session = sessions.get(session_id)
    if not session:
        raise HTTPException(404, "μ„Έμ…˜μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
    return {
        "file_name": session["file_name"],
        "df_info": session["df_info"],
        "preview": session["preview"],
    }


@app.post("/api/analyze")
async def analyze(req: AnalyzeRequest, background_tasks: BackgroundTasks):
    session = sessions.get(req.session_id)
    if not session:
        raise HTTPException(404, "μ„Έμ…˜μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")

    if not req.query.strip():
        raise HTTPException(400, "뢄석 μš”μ²­μ„ μž…λ ₯ν•΄μ£Όμ„Έμš”.")

    # Resolve previous results if follow-up
    prev_results = None
    if req.job_id:
        prev_job = jobs.get(req.job_id, {})
        prev_results = prev_job.get("results")

    job_id = str(uuid.uuid4())
    with _lock:
        jobs[job_id] = {
            "job_id": job_id,
            "session_id": req.session_id,
            "query": req.query,
            "status": "pending",
            "created_at": datetime.now().isoformat(),
            "completed_at": None,
            "code": None,
            "results": None,
            "files": [],
            "error": None,
            "stderr": None,
            "log": ["뢄석 μš”μ²­ μ ‘μˆ˜λ¨"],
        }

    background_tasks.add_task(
        run_analysis_job, job_id, req.session_id, req.query, prev_results
    )
    return {"job_id": job_id, "status": "pending"}


@app.get("/api/job/{job_id}")
async def get_job(job_id: str):
    job = jobs.get(job_id)
    if not job:
        raise HTTPException(404, "μž‘μ—…μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
    return job


@app.get("/api/download/{job_id}/{filename}")
async def download_file(job_id: str, filename: str):
    # Prevent path traversal
    safe_name = Path(filename).name
    path = RESULTS_DIR / job_id / safe_name
    if not path.exists():
        raise HTTPException(404, "νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
    return FileResponse(str(path), filename=safe_name)


@app.get("/api/session/{session_id}")
async def get_session(session_id: str):
    session = sessions.get(session_id)
    if not session:
        raise HTTPException(404, "μ„Έμ…˜μ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
    return {
        "session_id": session_id,
        "file_name": session["file_name"],
        "rows": session["df_info"]["shape"][0],
        "cols": session["df_info"]["shape"][1],
        "analyses": session["analyses"],
    }


# ── static + results file serving ─────────────────────────────
app.mount("/results", StaticFiles(directory=str(RESULTS_DIR)), name="results")
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")


# ──────────────────────────────────────────────────────────────
if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "main:app",
        host=os.getenv("HOST", "0.0.0.0"),
        port=int(os.getenv("PORT", 8000)),
        reload=True,   # 둜컬 개발용 β€” RenderλŠ” startCommandλ₯Ό μ‚¬μš©ν•˜λ―€λ‘œ λ¬΄μ‹œλ¨
    )