# SPDX-License-Identifier: GPL-3.0-or-later
"""Persistent 'My fleet' — a user-curated set of MMSIs (with last-known names),
kept as a small JSON file in the profile dir (like route_tol.json). Drives the
Vessels tab's My-fleet view and the map's 'plot my fleet only' filter.
"""
import json
import os


def _path():
    from .guardian_store import default_base_dir
    return os.path.join(default_base_dir(), "my_fleet.json")


def load():
    """{mmsi(str): name(str)} — empty on any problem."""
    try:
        with open(_path(), encoding="utf-8") as fh:
            d = json.load(fh)
        return {str(k): (v or "") for k, v in d.items()}
    except Exception:                              # noqa: BLE001
        return {}


def save(d):
    try:
        os.makedirs(os.path.dirname(_path()), exist_ok=True)
        with open(_path(), "w", encoding="utf-8") as fh:
            json.dump({str(k): (v or "") for k, v in d.items()}, fh, indent=0)
    except Exception:                              # noqa: BLE001  # nosec B110
        pass


def add(mmsi, name=None):
    """Add (or update the name of) a vessel; returns the updated dict."""
    d = load()
    d[str(mmsi)] = name or d.get(str(mmsi), "") or ""
    save(d)
    return d


def remove(mmsi):
    d = load()
    d.pop(str(mmsi), None)
    save(d)
    return d


def contains(mmsi):
    return str(mmsi) in load()


def mmsis():
    """Set of MMSIs currently in the fleet."""
    return set(load().keys())
