# Backend Integration Plan

## Objective
Implement the backend logic required to support the advanced dashboard features, including study creation, real-time data streaming, 3D mesh conversion, and report generation.

## 1. Enhanced WebSocket Real-Time Streaming
**File**: `atomizer-dashboard/backend/api/websocket/optimization_stream.py`

### Tasks
- [ ] Update `OptimizationFileHandler` to watch for `pareto_front` updates.
- [ ] Update `OptimizationFileHandler` to watch for `optimizer_state` updates.
- [ ] Implement broadcasting logic for new event types: `pareto_front`, `optimizer_state`.

## 2. Study Creation API
**File**: `atomizer-dashboard/backend/api/routes/optimization.py`

### Tasks
- [ ] Implement `POST /api/optimization/studies` endpoint.
- [ ] Add logic to handle multipart/form-data (config + files).
- [ ] Create study directory structure (`1_setup`, `2_results`, etc.).
- [ ] Save uploaded files (`.prt`, `.sim`, `.fem`) to `1_setup/model/`.
- [ ] Save configuration to `1_setup/optimization_config.json`.

## 3. 3D Mesh Visualization API
**File**: `atomizer-dashboard/backend/api/routes/optimization.py` & `optimization_engine/mesh_converter.py`

### Tasks
- [ ] Create `optimization_engine/mesh_converter.py` utility.
  - [ ] Implement `convert_to_gltf(bdf_path, op2_path, output_path)` function.
  - [ ] Use `pyNastran` to read BDF/OP2.
  - [ ] Use `trimesh` (or custom logic) to export GLTF.
- [ ] Implement `POST /api/optimization/studies/{study_id}/convert-mesh` endpoint.
- [ ] Implement `GET /api/optimization/studies/{study_id}/mesh/{filename}` endpoint.

## 4. Report Generation API
**File**: `atomizer-dashboard/backend/api/routes/optimization.py` & `optimization_engine/report_generator.py`

### Tasks
- [ ] Create `optimization_engine/report_generator.py` utility.
  - [ ] Implement `generate_report(study_id, format, include_llm)` function.
  - [ ] Use `markdown` and `weasyprint` (optional) for rendering.
- [ ] Implement `POST /api/optimization/studies/{study_id}/generate-report` endpoint.
- [ ] Implement `GET /api/optimization/studies/{study_id}/reports/{filename}` endpoint.

## 5. Dependencies
**File**: `atomizer-dashboard/backend/requirements.txt`

### Tasks
- [ ] Add `python-multipart` (for file uploads).
- [ ] Add `pyNastran` (for mesh conversion).
- [ ] Add `trimesh` (optional, for GLTF export).
- [ ] Add `markdown` (for report generation).
- [ ] Add `weasyprint` (optional, for PDF generation).

## Execution Order
1.  **Dependencies**: Update `requirements.txt` and install packages.
2.  **Study Creation**: Implement the POST endpoint to enable the Configurator.
3.  **WebSocket**: Enhance the stream to support advanced visualizations.
4.  **3D Pipeline**: Build the mesh converter and API endpoints.
5.  **Reporting**: Build the report generator and API endpoints.