from fastapi import FastAPI
from fastapi.responses import FileResponse
from app.api.endpoints import users, auth, messages, media
from app.websocket.connection_manager import wsRouter
from fastapi.middleware.cors import CORSMiddleware
import os
import asyncio
from app.db import models

app = FastAPI()

app.include_router(auth.authRouter)
app.include_router(users.usersRouter)
app.include_router(messages.messagesRouter)
app.include_router(media.mediaRouter)
app.include_router(wsRouter)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/check-update")
async def check_update():
    return {
        "latest_version": "2.0.0",
        "apk_url": "https://api.chepuhagram.ru/get-update",
        "force_update": False
    }


@app.get("/get-update")
async def get_image():
    file_path = "app-release.apk"
    if not os.path.exists(file_path):
        return {"error": "Файл не найден"}

    return FileResponse(path=file_path, filename="chepuhagram-release.apk",
                        media_type="application/vnd.android.package-archive",)


@app.head("/get-update")
async def head_image():
    file_path = "app-release.apk"
    if not os.path.exists(file_path):
        return {"error": "Файл не найден"}

    return FileResponse(path=file_path, filename="chepuhagram-release.apk",
                        media_type="application/vnd.android.package-archive",)


@app.on_event("startup")
async def startup_event():
    asyncio.create_task(cleanup_uploads())


async def cleanup_uploads():
    while True:
        try:
            db = models.SessionLocal()
            # Получить все используемые file_id из avatar_file_id
            file_ids = db.query(models.User.avatar_file_id).filter(models.User.avatar_file_id.isnot(None)).all()
            used_files = set(f[0] for f in file_ids)
            db.close()

            # Проверить файлы в uploads
            uploads_dir = 'uploads'
            if os.path.exists(uploads_dir):
                for filename in os.listdir(uploads_dir):
                    if filename.endswith('.enc'):
                        file_id = filename[:-4]  # убрать .enc
                        if file_id not in used_files:
                            file_path = os.path.join(uploads_dir, filename)
                            os.remove(file_path)
                            print(f"Удален неиспользуемый файл: {file_path}")
        except Exception as e:
            print(f"Ошибка в cleanup: {e}")
        await asyncio.sleep(300)  # каждые 5 минут

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8587)
