import type { TelemetrySnapshot } from "../../../types/telemetry";

export type ChartVariable = {
    key: string;
    sensorId: number;
    label: string;
    unit: string;
    value: TelemetrySnapshot["value"];
    timestamp: string;
    chartable: boolean;
    category: string;
    group: string;
};

export function toChartVariable(snapshot: TelemetrySnapshot): ChartVariable {
    return {
        key: snapshot.key,
        sensorId: snapshot.sensorId,
        label: snapshot.name,
        unit: snapshot.unit ?? "",
        value: snapshot.value,
        timestamp: snapshot.timestamp,
        chartable:
            typeof snapshot.value === "number" &&
            snapshot.bitOffset === null,
        category: getTelemetryCategory(snapshot),
        group: getTelemetryGroup(snapshot),
    };
}

function getTelemetryCategory(snapshot: TelemetrySnapshot): string {
    const key = snapshot.key.toLowerCase();
    const name = snapshot.name.toLowerCase();

    if (key.includes("temperature") || name.includes("temperatura")) return "Temperatura";
    if (key.includes("humidity") || name.includes("humidade")) return "Humidade";
    if (key.includes("co2") || name.includes("co2")) return "CO₂";
    if (key.includes("radiation") || name.includes("radiacao")) return "Radiação";
    if (key.includes("wind") || name.includes("vento")) return "Vento";
    if (key.includes("rain") || name.includes("chuva")) return "Chuva";
    if (key.includes("ph") || name.includes("ph")) return "pH";
    if (key.includes("ce") || name.includes("ce")) return "CE";
    if (key.includes("pressure") || name.includes("pressao")) return "Pressão";

    return "Outros";
}

function getTelemetryGroup(snapshot: TelemetrySnapshot): string {
    const key = snapshot.key.toLowerCase();
    const name = snapshot.name.toLowerCase();

    if (key.includes("exterior") || name.includes("exterior")) return "Exterior";

    const estufaMatch = name.match(/estufa\s*(\d+)/);
    if (estufaMatch) return `Estufa ${estufaMatch[1]}`;

    const controllerMatch = name.match(/\bc(\d+)\b/i);
    if (controllerMatch) return `Controlador C${controllerMatch[1]}`;

    const setorMatch = name.match(/setor\s*(\d+)/);
    if (setorMatch) return "Setores";

    return "Outros";
}