import os
import shutil

from models.model import Model


def _maybe_migrate_tab_json_to_zone():
    """One-time copy ``db/tab.json`` → ``db/zone.json`` when upgrading."""
    try:
        base = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        db_dir = os.path.join(base, "db")
        zone_path = os.path.join(db_dir, "zone.json")
        tab_path = os.path.join(db_dir, "tab.json")
        if not os.path.exists(zone_path) and os.path.exists(tab_path):
            shutil.copy2(tab_path, zone_path)
            print("Migrated db/tab.json -> db/zone.json")
    except OSError:
        pass


class Zone(Model):
    """Preset layout row (stored in ``db/zone.json``); legacy storage was ``tab.json`` / Tab."""

    def __init__(self):
        if not getattr(Zone, "_migration_checked", False):
            _maybe_migrate_tab_json_to_zone()
            Zone._migration_checked = True
        super().__init__()

    def create(self, name="", names=None, presets=None):
        next_id = self.get_next_id()
        self[next_id] = {
            "name": name,
            "names": names if names else [],
            "presets": presets if presets else [],
            "default_preset": None,
            "brightness": 255,
        }
        self.save()
        return next_id

    def read(self, id):
        id_str = str(id)
        return self.get(id_str, None)

    def update(self, id, data):
        id_str = str(id)
        if id_str not in self:
            return False
        self[id_str].update(data)
        self.save()
        return True

    def delete(self, id):
        id_str = str(id)
        if id_str not in self:
            return False
        self.pop(id_str)
        self.save()
        return True

    def list(self):
        return list(self.keys())
