# BMC Hub Module System - Quick Start Guide

## 🚀 Kom i gang på 5 minutter

### 1. Opret nyt modul

```bash
python3 scripts/create_module.py invoice_ocr "OCR scanning af fakturaer"
```

### 2. Kør database migration

```bash
docker-compose exec db psql -U bmc_hub -d bmc_hub -f app/modules/invoice_ocr/migrations/001_init.sql
```

Eller direkte:
```bash
psql -U bmc_hub -d bmc_hub -f app/modules/invoice_ocr/migrations/001_init.sql
```

### 3. Enable modulet

Rediger `app/modules/invoice_ocr/module.json`:
```json
{
  "enabled": true
}
```

### 4. Tilføj konfiguration (optional)

Tilføj til `.env`:
```bash
MODULES__INVOICE_OCR__READ_ONLY=false
MODULES__INVOICE_OCR__DRY_RUN=false
MODULES__INVOICE_OCR__API_KEY=secret123
```

### 5. Restart API

```bash
docker-compose restart api
```

### 6. Test din modul

**API Endpoint:**
```bash
curl http://localhost:8000/api/v1/invoice_ocr/health
```

**Web UI:**
```
http://localhost:8000/invoice_ocr
```

**API Documentation:**
```
http://localhost:8000/api/docs#Invoice-Ocr
```

## 📋 Hvad får du?

```
app/modules/invoice_ocr/
├── module.json              # ✅ Konfigureret med dit navn
├── README.md                # ✅ Dokumentation template
├── backend/
│   └── router.py            # ✅ 5 CRUD endpoints klar
├── frontend/
│   └── views.py             # ✅ HTML view route
├── templates/
│   └── index.html           # ✅ Bootstrap UI
└── migrations/
    └── 001_init.sql         # ✅ Database schema
```

## 🛠️ Byg din feature

### API Endpoints (backend/router.py)

```python
@router.get("/invoice_ocr/scan")
async def scan_invoice(file_path: str):
    """Scan en faktura med OCR"""
    
    # Check safety switch
    read_only = get_module_config("invoice_ocr", "READ_ONLY", "true")
    if read_only == "true":
        return {"error": "READ_ONLY mode"}
    
    # Din logik her
    result = perform_ocr(file_path)
    
    # Gem i database (bemærk table prefix!)
    invoice_id = execute_insert(
        "INSERT INTO invoice_ocr_scans (file_path, text) VALUES (%s, %s)",
        (file_path, result)
    )
    
    return {"success": True, "invoice_id": invoice_id}
```

### Frontend View (frontend/views.py)

```python
@router.get("/invoice_ocr", response_class=HTMLResponse)
async def ocr_page(request: Request):
    """OCR scan interface"""
    
    scans = execute_query(
        "SELECT * FROM invoice_ocr_scans ORDER BY created_at DESC"
    )
    
    return templates.TemplateResponse("index.html", {
        "request": request,
        "scans": scans
    })
```

### Database Tables (migrations/001_init.sql)

```sql
-- Husk table prefix!
CREATE TABLE invoice_ocr_scans (
    id SERIAL PRIMARY KEY,
    file_path VARCHAR(500),
    extracted_text TEXT,
    confidence FLOAT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

## 🔒 Safety First

Alle moduler starter med safety switches ENABLED:

```bash
MODULES__YOUR_MODULE__READ_ONLY=true   # Bloker alle writes
MODULES__YOUR_MODULE__DRY_RUN=true     # Log uden at udføre
```

Disable når du er klar til production:

```bash
MODULES__YOUR_MODULE__READ_ONLY=false
MODULES__YOUR_MODULE__DRY_RUN=false
```

## 📊 Monitor din modul

### List alle moduler
```bash
curl http://localhost:8000/api/v1/modules
```

### Module health check
```bash
curl http://localhost:8000/api/v1/invoice_ocr/health
```

### Check logs
```bash
docker-compose logs -f api | grep invoice_ocr
```

## 🐛 Troubleshooting

### Modul vises ikke i API docs

1. Check at `enabled: true` i module.json
2. Restart API: `docker-compose restart api`
3. Check logs: `docker-compose logs api`

### Database fejl

1. Verify migration ran: `psql -U bmc_hub -d bmc_hub -c "\d invoice_ocr_scans"`
2. Check table prefix matcher module.json
3. Se migration errors i logs

### Import fejl

Sørg for `__init__.py` findes:
```bash
touch app/modules/invoice_ocr/backend/__init__.py
touch app/modules/invoice_ocr/frontend/__init__.py
```

## 📚 Næste Steps

1. **Læs fuld dokumentation:** [docs/MODULE_SYSTEM.md](MODULE_SYSTEM.md)
2. **Se template eksempel:** `app/modules/_template/`
3. **Check API patterns:** `backend/router.py` i template
4. **Lær database helpers:** `app/core/database.py`

## 💡 Tips

- Start med simple features og byg op
- Brug safety switches i development
- Test lokalt før enable i production
- Log alle actions med emoji (🔄 ✅ ❌)
- Dokumenter API endpoints i docstrings
- Version dine migrations (001, 002, 003...)

## ❓ Hjælp

**Logs:** `logs/app.log`
**Issues:** Se [MODULE_SYSTEM.md](MODULE_SYSTEM.md#troubleshooting)
**Template:** `app/modules/_template/`

---

**Happy coding! 🎉**
