from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from utils.pictures_handle import get_pictures_info
from utils.pictures_handle import get_total_pages
import os
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="pictures"), name="static")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],  # 允许的源列表
    allow_credentials=True,
    allow_methods=["*"],  # 允许的方法
    allow_headers=["*"],  # 允许的头
)


@app.get("/")
async def root():
    return "welcome to fastAPI!"


@app.get("/api/get-menu")
async def get_menu():
    menu_list = [
        {"id": 1, "menu_name": "首页", "url": "/", "src": "/index.svg"},
        {"id": 2, "menu_name": "图片", "url": "/photos", "src": "/photo.svg"},
        {"id": 3, "menu_name": "视频", "url": "/videos", "src": "/videos.svg"},
        {"id": 4, "menu_name": "关于", "url": "/about", "src": "/about.svg"}
    ]
    return {
        "code": 0,
        "msg": "ok",
        "data": menu_list
    }


@app.get("/api/get-photo-list")
async def get_photo_list(page: int = 1, page_size: int = 10):
    dir_path = "pictures"
    total_pages = get_total_pages(dir_path, page_size)
    photo_list = get_pictures_info(dir_path, page, page_size)
    for photo in photo_list:
        photo["photo_url"] = f"http://127.0.0.1:8000/static/{photo['photo_name']}"
    return {
        "code": 0,
        "msg": "ok",
        "data": photo_list,
        "page_count": total_pages
    }


@app.get("/static/{photo_name}")
async def get_photo(photo_name: str,request: Request):
    request_path = str(request.url)
    dir = "pictures"
    file_path = os.path.join(dir, photo_name)
    if os.path.exists(file_path):
        return FileResponse(file_path)
    else:
        print(f"ERROR: {request_path}")
        return {
            "code": -1,
            "msg": "error",
            "data": None
        }
