import os
import zipfile
import datetime

def is_ignored(rel_path, ignore_patterns):
    """
    检查路径是否匹配 .packignore 中的忽略规则
    """
    rel_path = rel_path.replace('\\', '/')
    for pattern in ignore_patterns:
        if pattern.endswith('/'):
            if rel_path.startswith(pattern) or rel_path + '/' == pattern:
                return True
        else:
            if rel_path == pattern or rel_path.startswith(pattern + '/'):
                return True
            if '/' not in pattern:
                if rel_path == pattern or rel_path.endswith('/' + pattern):
                    return True
    return False

def main():
    # 获取根目录（假设脚本在根目录的子文件夹中，或者直接在根目录）
    # 根据你的原代码逻辑，这里指向脚本上一级文件夹的上一级，请根据实际位置调整
    root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    packignore_file = os.path.join(root_dir, '.packignore')
    
    ignore_patterns = []
    if os.path.exists(packignore_file):
        with open(packignore_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#'):
                    ignore_patterns.append(line.replace('\\', '/'))
                    
    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    base_name = f"mota_pack_{timestamp}"
    output_filename = f"{base_name}.zip"
    output_path = os.path.join(root_dir, output_filename)
    
    # 这就是你想要的“外面套的一层文件夹”的名字
    # 我们通常使用不带.zip后缀的文件名作为内层根目录
    inner_root_folder = base_name

    print(f"Packing into {output_filename}...")
    print(f"Archive internal structure will start with: {inner_root_folder}/")
    
    count = 0
    with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        for foldername, subfolders, filenames in os.walk(root_dir):
            # 获取相对路径
            rel_folder = os.path.relpath(foldername, root_dir).replace('\\', '/')
            if rel_folder == '.':
                rel_folder = ''
                
            # 过滤子文件夹，防止 os.walk 进入被忽略的目录
            subfolders[:] = [d for d in subfolders if not is_ignored((rel_folder + '/' + d).strip('/'), ignore_patterns)]
            
            for filename in filenames:
                # 构造文件在项目中的相对路径
                rel_file = (rel_folder + '/' + filename).strip('/')
                
                # 始终忽略生成的压缩包本身，防止递归包含
                if filename.startswith("mota_pack_") and filename.endswith(".zip"):
                    continue
                    
                if not is_ignored(rel_file, ignore_patterns):
                    abs_path = os.path.join(foldername, filename)
                    
                    # 关键修改点：在 arcname 前面拼接上 inner_root_folder
                    # 这样压缩包内的路径就会变成 "mota_pack_xxx/path/to/file"
                    arc_path = os.path.join(inner_root_folder, rel_file)
                    
                    zf.write(abs_path, arc_path)
                    count += 1
                    
    print(f"Done! Packed {count} files.")
    print(f"Output: {output_path}")

if __name__ == "__main__":
    main()