#
# Erminig - Création et mise à jour de la révision des fichiers pakva
# Copyright (C) 2025 L0m1g
# Sous licence DOUARN - Voir le fichier LICENCE pour les détails
#
# Ce fichier fait partie du projet Erminig.
# Libre comme l’air, stable comme un menhir, et salé comme le beurre.
#

from pathlib import Path
from erminig.config import Config
from erminig.system.security import run_as_user


class Pakva:

    def __init__(self, name, version, archive):
        self.name = name
        self.version = version
        self.archive = archive
        self.path = Config.GOVEL_DIR / name[0] / name / "Pakva"

    @run_as_user("pak")
    def save(self):
        self.path.parent.mkdir(parents=True, exist_ok=True)
        with open(self.path, "w") as f:
            f.write(
                f"""\
name="{self.name}"
version="{self.version}"
revision=1
source=("{self.archive}")

build() {{
    echo "Build function not implemented"
}}

pak() {{
    echo "Packaging function not implemented"
}}               
"""
            )

    @run_as_user("pak")
    def update_version(self, version, archive, reset_revision=False):
        if not self.path.exists():
            raise FileNotFoundError(f"Aucun fichier Pakva pour {self.name}")

        with open(self.path, "r") as f:
            lines = f.readlines()

        new_lines = []
        updated_version = False
        updated_source = False

        for line in lines:
            if line.startswith("version=") and not updated_version:
                new_lines.append(f'version="{version}"\n')
                updated_version = True
            elif line.startswith("source=") and not updated_source:
                new_lines.append(f'source=("{archive}")\n')
                updated_source = True
            elif reset_revision and line.startswith("revision="):
                new_lines.append("revision=1\n")
            else:
                new_lines.append(line)

        # Ajout si jamais les champs n'existaient pas
        if not updated_version:
            new_lines.insert(1, f'version="{version}"\n')
        if not updated_source:
            new_lines.append(f'source=("{archive}")\n')
        if reset_revision and not any(line.startswith("revision=") for line in lines):
            new_lines.insert(2, "revision=1\n")

        with open(self.path, "w") as f:
            f.writelines(new_lines)

        self.version = version
        self.archive = archive
        print(f"[Pakva] Version mise à jour pour {self.name} -> {version}")

    @classmethod
    def read(cls, path):
        """
        Lit un fichier Pakva et retourne un objet Pakva.
        """
        path = Path(path)
        if not path.exists():
            raise FileNotFoundError(f"Fichier Pakva introuvable : {path}")

        with path.open() as f:
            lines = f.readlines()

        name = None
        version = None
        archive = None

        for line in lines:
            if line.startswith("name="):
                name = line.split("=")[1].strip().strip('"')
            elif line.startswith("version="):
                version = line.split("=")[1].strip().strip('"')
            elif line.startswith("source=("):
                archive = line.split("(")[1].split(")")[0].strip().strip('"')

        obj = cls(name, version, archive)
        obj.path = path
        return obj

    def __repr__(self):
        return f"<Pakva {self.name}-{self.version}>"
