import os
import subprocess
from datetime import datetime

from db import db, Job, Run


def read_archive_info(archive_name, backup_dir):
    """Lit les métadonnées d'une archive (backup_info.json embarqué + fallback Run table)."""
    archive_path = os.path.join(backup_dir, archive_name + ".tar")
    from jobs.utils import sudo_read_backup_info
    info = sudo_read_backup_info(archive_path)
    if not info.get("type"):
        run = Run.query.filter_by(archive_name=archive_name).first()
        if run:
            job = db.session.get(Job, run.job_id)
            if job:
                info["type"] = job.type
                info["_from_run"] = True
    return info


def get_ynh_apps(exclude_app_ids=None):
    """Retourne la liste des apps YunoHost installées, en excluant celles déjà utilisées."""
    try:
        import json
        result = subprocess.run(
            ["sudo", "yunohost", "app", "list", "--output-as", "json"],
            capture_output=True, text=True, timeout=15,
        )
        if result.returncode == 0:
            apps = json.loads(result.stdout).get("apps", [])
            if exclude_app_ids:
                apps = [a for a in apps if a.get("id") not in exclude_app_ids]
            return apps
    except Exception:
        pass
    return []
