from fastapi import FastAPI, Request, BackgroundTasks from fastapi.staticfiles import StaticFiles import json from processing_logic import run_email_processing from fastapi.responses import FileResponse app = FastAPI() # Mount the 'web' directory to serve static files (CSS, JS) app.mount("/static", StaticFiles(directory="web"), name="static") @app.get("/") def read_root(): """Serves the main index.html file.""" return FileResponse('web/index.html') @app.get("/api/rules") def get_rules(): """Reads and returns the current rules from rules.json.""" try: with open('rules.json', 'r', encoding='utf-8') as f: return json.load(f) except FileNotFoundError: return {"error": "rules.json not found"} except json.JSONDecodeError: return {"error": "Could not parse rules.json"} @app.post("/api/rules") async def save_rules(request: Request): """Receives new rules as JSON and overwrites rules.json.""" try: new_rules = await request.json() with open('rules.json', 'w', encoding='utf-8') as f: json.dump(new_rules, f, indent=2, ensure_ascii=False) return {"message": "Rules saved successfully."} except json.JSONDecodeError: return {"error": "Invalid JSON format received."} except Exception as e: return {"error": f"An error occurred: {e}"} @app.post("/api/run-processing") async def trigger_processing(background_tasks: BackgroundTasks): """Triggers the email processing task in the background.""" background_tasks.add_task(run_email_processing) return {"message": "Email processing task has been started in the background."} if __name__ == "__main__": import uvicorn # This is for local development. For production, you'd run uvicorn directly. uvicorn.run(app, host="0.0.0.0", port=8000)