#!/bin/bash
# 🚀 SERVICE FINDER - SMART TILES & NAS BACKUP SCRIPT (V16.0)

PROJECT_ROOT="/opt/service_finder"
NAS_BACKUP_PATH="/mnt/nas/app_data/backups"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

echo "--- 📦 1. BIZTONSÁGI MENTÉS KÉSZÍTÉSE A NAS-RA ---"
mkdir -p $NAS_BACKUP_PATH
# Mentés a NAS-ra a változtatások előtt
tar -czf $NAS_BACKUP_PATH/sf_backup_$TIMESTAMP.tar.gz -C $PROJECT_ROOT backend/app
echo "✅ Mentés elkészült: $NAS_BACKUP_PATH/sf_backup_$TIMESTAMP.tar.gz"

echo "--- ⚙️ 2. VERZIÓ ÉS CHANGELOG FRISSÍTÉSE ---"
cat <<EOF >> $PROJECT_ROOT/CHANGELOG.md
## [16.0] - 2026-01-25
### Hozzáadva
- Smart Tiles: Csempe alapú nézet a Dashboardon.
- Brand logók és okmány-lejárat figyelmeztetések.
- Automata NAS mentés funkció a telepítőben.
EOF

echo "--- 🧠 3. BACKEND FRISSÍTÉSE (fleet.py) ---"
cat <<EOF > $PROJECT_ROOT/backend/app/api/v1/endpoints/fleet.py
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from typing import List
from app.db.session import get_db
from app.schemas.fleet import VehicleCreate, VehicleResponse, EventCreate, EventResponse
from app.models.vehicle import UserVehicle 
from app.models.system_settings import SystemSetting 
from app.models.vehicle_event import VehicleEvent 
from app.api.deps import get_current_user
from app.models.user import User

router = APIRouter()

@router.get("/vehicles", response_model=List[VehicleResponse])
async def get_my_vehicles(db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user)):
    result = await db.execute(select(UserVehicle).where(UserVehicle.user_id == current_user.id))
    return result.scalars().all()

@router.post("/vehicles/{vehicle_id}/events", response_model=EventResponse)
async def create_event(vehicle_id: int, event_in: EventCreate, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user)):
    v_query = await db.execute(select(UserVehicle).where(UserVehicle.id == vehicle_id, UserVehicle.user_id == current_user.id))
    vehicle = v_query.scalar_one_or_none()
    if not vehicle:
        raise HTTPException(status_code=404, detail="Jármű nem található.")
    if event_in.odometer < vehicle.current_odometer:
        raise HTTPException(status_code=400, detail=f"Hiba: Km állás ({event_in.odometer}) kevesebb mint {vehicle.current_odometer}")
    new_event = VehicleEvent(**event_in.model_dump(), vehicle_id=vehicle_id)
    db.add(new_event)
    vehicle.current_odometer = event_in.odometer
    await db.commit()
    await db.refresh(new_event)
    return new_event
EOF

echo "--- 🎨 4. FRONTEND FRISSÍTÉSE (dashboard.html) ---"
cat <<EOF > $PROJECT_ROOT/backend/app/static/dashboard.html
<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8"><title>Service Finder - Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #0f172a; color: white; }
        .vehicle-tile { background: #1e293b; border-radius: 15px; padding: 20px; border: 1px solid #334155; transition: 0.3s; position: relative; }
        .vehicle-tile:hover { transform: translateY(-5px); border-color: #3b82f6; }
        .brand-logo { width: 40px; height: 40px; margin-right: 10px; opacity: 0.8; }
        .alert-icon { position: absolute; top: 10px; right: 10px; font-size: 1.5rem; }
    </style>
</head>
<body class="p-4">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-5">
            <h1 style="font-weight: 900;">GARÁZS</h1>
            <button class="btn btn-primary" onclick="location.href='register_vehicle.html'">+ ÚJ JÁRMŰ</button>
        </div>
        <div id="vehicleList" class="row g-4">
            </div>
    </div>

    <script>
        const TOKEN = localStorage.getItem('token');
        if (!TOKEN) window.location.href = 'login.html';

        async function loadVehicles() {
            const res = await fetch('/api/v1/fleet/vehicles', {
                headers: { 'Authorization': 'Bearer ' + TOKEN }
            });
            const vehicles = await res.json();
            const container = document.getElementById('vehicleList');
            container.innerHTML = '';

            vehicles.forEach(v => {
                // Egyszerű logika a figyelmeztetésekhez (Backend hivatkozás helyett egyelőre itt)
                let alertHtml = v.current_odometer > 150000 ? '<span class="alert-icon">🔴</span>' : '';
                
                container.innerHTML += \`
                    <div class="col-md-4">
                        <div class="vehicle-tile shadow">
                            \${alertHtml}
                            <div class="d-flex align-items-center mb-3">
                                <img src="https://logo.clearbit.com/\${v.make.toLowerCase()}.com" class="brand-logo" onerror="this.src='https://via.placeholder.com/40?text=🚗'">
                                <h4 class="m-0">\${v.license_plate}</h4>
                            </div>
                            <p class="text-info mb-1">\${v.make} \${v.model} (\${v.year})</p>
                            <p class="small text-muted">Aktuális km: <strong>\${v.current_odometer} km</strong></p>
                            <button class="btn btn-sm btn-outline-light w-100 mt-2">ADATLAP ÉS KÖLTSÉG</button>
                        </div>
                    </div>
                \`;
            });
        }
        loadVehicles();
    </script>
</body>
</html>
EOF

echo "--- 🔄 5. RENDSZER ÚJRAINDÍTÁSA ---"
docker compose restart service_finder_api
echo "🚀 FRISSÍTÉS ÉS NAS MENTÉS SIKERES!"
