from fastapi import FastAPI, BackgroundTasks, HTTPException
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from contextlib import asynccontextmanager
import uvicorn
import os

from client import SnapchatClient
from backend import scraper_service

# Lifespan event to manage background scraper
@asynccontextmanager
async def lifespan(app: FastAPI):
    # Start the Playwright scraper in a background thread
    scraper_service.start()
    yield
    # Stop the scraper gracefully when shutting down
    scraper_service.running = False

app = FastAPI(title="Snapchat Private API", lifespan=lifespan)

# Initialize the public client
snap_client = SnapchatClient(headless=True)

# Mount static files for the UI
# Assuming the root directory contains snapchat_ui.html
app.mount("/static", StaticFiles(directory="."), name="static")

@app.get("/")
def get_ui():
    """Serve the static UI"""
    if os.path.exists("snapchat_ui.html"):
        return FileResponse("snapchat_ui.html")
    return {"error": "snapchat_ui.html not found"}

@app.get("/decrypted_messages.json")
def get_decrypted_messages():
    """Serve the static JSON file for the UI"""
    if os.path.exists("decrypted_messages.json"):
        return FileResponse("decrypted_messages.json")
    return {"chat_list": [], "messages": []}

@app.get("/api/public/profile/{username}")
def get_public_profile(username: str):
    """Get public profile information for a user."""
    data = snap_client.get_profile(username)
    if not data:
        raise HTTPException(status_code=404, detail="User not found or no profile data")
    return data

@app.get("/api/public/stories/{username}")
def get_public_stories(username: str):
    """Get active public stories for a user."""
    data = snap_client.get_stories(username)
    if not data:
        raise HTTPException(status_code=404, detail="User not found or no stories")
    return data

@app.get("/api/public/highlights/{username}")
def get_public_highlights(username: str):
    """Get curated and spotlight highlights for a user."""
    data = snap_client.get_highlights(username)
    if not data:
        raise HTTPException(status_code=404, detail="User not found or no highlights")
    return data

@app.get("/api/private/chats")
def get_private_chats():
    """Get the recent chats list from the authenticated session."""
    data = scraper_service.get_latest_data()
    return {"chats": data.get("chat_list", [])}

@app.get("/api/private/messages")
def get_private_messages():
    """Get the currently opened conversation's messages."""
    data = scraper_service.get_latest_data()
    return {"messages": data.get("messages", [])}

if __name__ == "__main__":
    uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=True)
