import os
import sys

# 한글 환경 및 Tesseract 경로 강제 설정
os.environ["PYTHONIOENCODING"] = "utf-8"
os.environ["TESSDATA_PREFIX"] = r"C:\Users\User\AppData\Local\Programs\Tesseract-OCR\tessdata"

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from analyze import analyze_file_content
from crawler_service import run_crawler_service

app = FastAPI(title="Project Master Overseas API")

# 정적 파일 및 미들웨어 설정
app.mount("/style", StaticFiles(directory="style"), name="style")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=False,
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- HTML 라우팅 ---
@app.get("/")
async def root():
    return FileResponse("index.html")

@app.get("/dashboard")
async def get_dashboard():
    return FileResponse("dashboard.html")

@app.get("/mailTest")
@app.get("/mailTest.html")
async def get_mail_test():
    return FileResponse("mailTest.html")

# --- 데이터 API ---
@app.get("/attachments")
async def get_attachments():
    sample_path = "sample"
    if not os.path.exists(sample_path):
        os.makedirs(sample_path)
    files = []
    for f in os.listdir(sample_path):
        f_path = os.path.join(sample_path, f)
        if os.path.isfile(f_path):
            files.append({
                "name": f,
                "size": f"{os.path.getsize(f_path) / 1024:.1f} KB"
            })
    return files

@app.get("/analyze-file")
async def analyze_file(filename: str):
    """
    분석 서비스(analyze.py) 호출
    """
    return analyze_file_content(filename)

@app.get("/sync")
async def sync_data():
    """
    크롤링 서비스(crawler_service.py) 호출
    """
    return StreamingResponse(run_crawler_service(), media_type="text_event-stream")
