import csv
import os
import sys
from datetime import datetime

def _app_root():
    if getattr(sys, "frozen", False):
        return os.path.dirname(sys.executable)  # pasta do .exe
    return os.path.dirname(os.path.abspath(__file__))  # pasta do projeto

APP_ROOT = _app_root()
DATA_DIR = os.path.join(APP_ROOT, "data")

def _ensure_data_dir():
    os.makedirs(DATA_DIR, exist_ok=True)

def _csv_filename():
    date_str = datetime.now().strftime("%Y-%m-%d")
    return os.path.join(DATA_DIR, f"production_{date_str}.csv")

def append_production_row(
    deveui: str,
    appkey: str,
    model: str,
    lote: str,
    box_id: str,
):
    _ensure_data_dir()

    file_path = _csv_filename()
    file_exists = os.path.isfile(file_path)

    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    row = [now, deveui, appkey, model, lote, box_id]

    with open(file_path, "a", newline="", encoding="utf-8-sig") as f:
        writer = csv.writer(
            f,
            delimiter=";",              # ✅ Excel PT-BR reconhece automático
            quoting=csv.QUOTE_MINIMAL
        )

        if not file_exists:
            writer.writerow(["DATA_HORA", "DEVEUI", "APPKEY", "MODELO", "LOTE", "CAIXA"])

        writer.writerow(row)
