#!/usr/bin/env python3
# fempkg - a simple package manager
# Copyright (C) 2026 Gabriel Di Martino
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import json, os
from pathlib import Path

DB_PATH = "/var/lib/fempkg/db.json"
Path(os.path.dirname(DB_PATH)).mkdir(parents=True, exist_ok=True)

def load_db():
    if os.path.exists(DB_PATH):
        with open(DB_PATH, "r") as f:
            return json.load(f)
    return {"installed": {}}

def save_db(db):
    with open(DB_PATH, "w") as f:
        json.dump(db, f, indent=2)

def register_package(name, version, db=None):
    if db is None:
        db = load_db()
    db["installed"][name] = version
    save_db(db)
    print(f"Registered: {name}-{version}")

def is_installed(name, version=None, db=None):
    if db is None:
        db = load_db()
    installed_ver = db["installed"].get(name)
    if installed_ver is None:
        return False
    if version:
        return installed_ver == version
    return True

