from fastapi import FastAPI, HTTPException, WebSocket
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
import uvicorn
import logging
from typing import Dict, List, Any
import json
from database_engineer import AutomaticDatabaseEngineer
app = FastAPI(title="Ingénieur DB Automatique", version="1.0.0")
db_engineer = AutomaticDatabaseEngineer()
class DatabaseConnection(BaseModel):
db_type: str
host: str = "localhost"
port: int = None
database: str
username: str = None
password: str = None
class SQLQuery(BaseModel):
connection_id: str
query: str
auto_fix: bool = True
@app.get("/", response_class=HTMLResponse)
def engineer_interface():
return """
Ingénieur DB Automatique
🧠 Ingénieur Base de Données Automatique
🚀 Optimisation Automatique
"""
@app.post("/api/connect")
async def connect_database(connection: DatabaseConnection):
try:
connection_id = await db_engineer.connect_database(
connection.db_type,
connection.dict()
)
return {"success": True, "connection_id": connection_id}
except Exception as e:
return {"success": False, "error": str(e)}
@app.post("/api/execute")
async def execute_query(query: SQLQuery):
result = await db_engineer.execute_and_fix_query(
query.connection_id,
query.query,
query.auto_fix
)
return result
@app.post("/api/optimize/{connection_id}")
async def optimize_database(connection_id: str):
result = await db_engineer.auto_optimize_database(connection_id)
return result
@app.post("/api/migrate/{connection_id}")
async def migrate_database(connection_id: str, target_schema: Dict):
result = await db_engineer.intelligent_migration(connection_id, target_schema)
return result
@app.websocket("/ws/monitor/{connection_id}")
async def websocket_monitor(websocket: WebSocket, connection_id: str):
await websocket.accept()
try:
while True:
monitoring_data = await db_engineer.real_time_monitoring(connection_id)
await websocket.send_json(monitoring_data)
await asyncio.sleep(5) # Update every 5 seconds
except Exception as e:
logging.error(f"WebSocket error: {e}")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)