#!/usr/bin/env python3
"""
解包DCI图标脚本 - 通过系统通知提示结果。
用法: extractdci.sh <DCI文件路径>
"""

import sys
import os
import subprocess
import tempfile
import shutil


DCI_BIN = "/usr/libexec/dtk6/DCore/bin/dci"

def notify(title, message, icon="emblem-checked"):
    subprocess.run([
        "notify-send",
        "--app-name=解包DCI",
        title,
        message,
        f"--icon={icon}"
    ])


def main():
    try:
        if len(sys.argv) < 2:
            notify("", "失败", "dialog-error")
            sys.exit(1)

        filepath = sys.argv[1]
        if filepath.startswith("file://"):
            filepath = filepath[7:]

        if not os.path.isfile(filepath):
            notify("", "失败", "dialog-error")
            sys.exit(1)

        if not os.access(DCI_BIN, os.X_OK):
            notify("", "失败", "dialog-error")
            sys.exit(1)

        basename = os.path.splitext(os.path.basename(filepath))[0]
        filedir = os.path.dirname(filepath)
        outdir = os.path.join(filedir, basename)

        if not os.access(filedir, os.W_OK):
            sys.exit(0)

        if os.path.isdir(outdir):
            shutil.rmtree(outdir)
        os.makedirs(outdir, exist_ok=True)

        with tempfile.TemporaryDirectory(prefix="dci_extract_") as tmpdir:
            subprocess.run([DCI_BIN, "--export", tmpdir, filepath], check=True)
            for item in os.listdir(tmpdir):
                src = os.path.join(tmpdir, item)
                dst = os.path.join(filedir, item)
                if os.path.isdir(src):
                    shutil.copytree(src, dst, dirs_exist_ok=True)
                else:
                    shutil.copy2(src, dst)

        notify("", "成功", "emblem-checked")

    except Exception:
        notify("", "失败", "dialog-error")
        sys.exit(1)


if __name__ == "__main__":
    main()
