#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
扫描指定 HOOKS_ROOT 下的可执行程序，并封装为 PostAction
优先级按照文件名前缀数字来决定，不带数字的默认 100
"""

import os
import logging
from typing import List, Dict
from SystemUpdater.UpdatesAvailable import PostAction
from SystemUpdater.constants import CURRENT_PROGRESS,MANIFESTS_DIR

HOOKS_ROOTS: List[str] = [
    os.path.join(CURRENT_PROGRESS, MANIFESTS_DIR.lstrip('/'), "hooks"),   # 原有目录
    "/opt/update-module/hooks",                                           # 新增目录
]

# HOOKS_ROOT 下要扫描的子目录
DIRECTORY_GROUPS: List[str] = [
    "pre-deploy.d",
    "post-deploy.d",
    "pre-check.d",
    "post-check.d",
]

def parse_priority(filename: str, default: int = 100) -> int:
    """
    从文件名前缀提取优先级，例如 "10-xxx.sh" -> 10
    不带数字前缀的默认 100
    """
    prefix = filename.split("-", 1)[0]
    return int(prefix) if prefix.isdigit() else default

def scan_hooks(hooks_roots: List[str] = HOOKS_ROOTS, directories: List[str] = DIRECTORY_GROUPS) -> Dict[str, List[PostAction]]:
    """
    扫描多个 HOOKS_ROOT 下的目录，返回 {目录名: PostAction 列表}
    """
    results: Dict[str, List[PostAction]] = {d: [] for d in directories}

    try:
        for hooks_root in hooks_roots:
            for d in directories:
                full_dir = os.path.join(hooks_root, d)
                if not os.path.isdir(full_dir):
                    continue

                for f in os.listdir(full_dir):
                    path = os.path.join(full_dir, f)
                    if os.path.isfile(path):  # 只接受可执行文件
                        priority = parse_priority(f)
                        action = PostAction(
                            command=path,
                            value="",
                            priority=priority,
                        )
                        results[d].append(action)
                        logging.info("Directory [%s] found executable: %s (priority=%d)", d, path, priority)

        # 每个目录内按 priority 排序
        for d in results:
            results[d].sort(key=lambda a: a.priority)
        
        return results
    except Exception as e:
        logging.error("Error accessing hooks directories: %s", e)
        return {d: [] for d in directories}