import ktc
import os
import shutil
import subprocess

# 設定 `.bie` 和 `.nef` 的存放目錄
onnx_dir = "runs/train/exp24/weights/"
bie_file = os.path.join(onnx_dir, "input.kdp720.scaled.bie")  # 確保 `.bie` 路徑正確

# 確保 `.bie` 檔案存在
if not os.path.exists(bie_file):
    raise FileNotFoundError(f"❌ Error: BIE file not found at {bie_file}")

print(f"✅ Found BIE file: {bie_file}")

# 初始化 ModelConfig
km = ktc.ModelConfig(20008, "0001", "720", bie_path=bie_file)

# 執行 `.nef` 轉換
nef_model_path = ktc.compile([km])

# 打印出 `.nef` 生成的路徑
print(f"🔍 Generated NEF file at: {nef_model_path}")

# 確保 `.nef` 轉換成功
if not nef_model_path or not os.path.exists(nef_model_path):
    raise RuntimeError(f"❌ Error: NEF model was not generated at {nef_model_path}")

# 確保目標資料夾存在
os.makedirs(onnx_dir, exist_ok=True)

# 移動 `.nef` 到指定資料夾
nef_save_path = os.path.join(onnx_dir, os.path.basename(nef_model_path))
shutil.copy(nef_model_path, nef_save_path)

# **立即檢查 `.nef` 是否真的存在**
if os.path.exists(nef_save_path):
    print(f"\n✅ NEF file successfully saved to: {nef_save_path}")
else:
    raise RuntimeError(f"❌ Error: NEF file NOT found in {nef_save_path} after copying!")

# **執行 `ls` 指令來確認 Python 內部真的看到 `.nef`**
print("\n🔍 Listing files in target directory:")
subprocess.run(["ls", "-lh", onnx_dir])
