from fastapi import FastAPI, UploadFile, File, Header, HTTPException
import shutil
from pathlib import Path
import os
import dropbox
from dotenv import load_dotenv

load_dotenv(Path(__file__).parent / ".env")

app = FastAPI()

TOKEN = "13e1bb01-9fd5-44a8-8ce9-4ee27133d340"
SAVE_DIR = Path("/msgs")
DB_DIR = Path("/msgs/db")

SAVE_DIR.mkdir(parents=True, exist_ok=True)
DB_DIR.mkdir(parents=True, exist_ok=True)

DROPBOX_APP_KEY = os.getenv("DROPBOX_APP_KEY", "")
DROPBOX_APP_SECRET = os.getenv("DROPBOX_APP_SECRET", "")
DROPBOX_REFRESH_TOKEN = os.getenv("DROPBOX_APP_REFRESH_TOKEN", "")


@app.post("/upload")
async def upload_msg(
    file: UploadFile = File(...),
    authorization: str = Header(None)
):
    if authorization != f"Bearer {TOKEN}":
        raise HTTPException(status_code=401, detail="Unauthorized")
    if not file.filename.endswith(".msg"):
        raise HTTPException(status_code=400, detail="Only .msg files accepted")
    dest = SAVE_DIR / file.filename
    if dest.exists():
        return {"status": "exists", "file": file.filename}
    with dest.open("wb") as f:
        shutil.copyfileobj(file.file, f)
    return {"status": "saved", "file": file.filename}


@app.post("/upload-db")
async def upload_db(
    file: UploadFile = File(...),
    authorization: str = Header(None)
):
    if authorization != f"Bearer {TOKEN}":
        raise HTTPException(status_code=401, detail="Unauthorized")
    if not file.filename.endswith(".db"):
        raise HTTPException(status_code=400, detail="Only .db files accepted")
    dest = DB_DIR / file.filename
    with dest.open("wb") as f:
        shutil.copyfileobj(file.file, f)
    return {"status": "saved", "file": file.filename}


@app.post("/upload-dropbox")
async def upload_dropbox(
    file: UploadFile = File(...),
    authorization: str = Header(None),
):
    if authorization != f"Bearer {TOKEN}":
        raise HTTPException(status_code=401, detail="Unauthorized")
    if not DROPBOX_REFRESH_TOKEN:
        raise HTTPException(status_code=500, detail="Dropbox not configured")

    content = await file.read()
    dbx = dropbox.Dropbox(
        app_key=DROPBOX_APP_KEY,
        app_secret=DROPBOX_APP_SECRET,
        oauth2_refresh_token=DROPBOX_REFRESH_TOKEN,
    )
    dropbox_path = f"/!!!Days/Downloads Z230/{file.filename}"
    dbx.files_upload(content, dropbox_path, mode=dropbox.files.WriteMode.overwrite)
    return {"status": "uploaded", "file": file.filename, "dropbox_path": dropbox_path}
