import os
import json
from psd_tools import PSDImage

def extract_layer_info(psd_path):
    psd = PSDImage.open(psd_path)
    canvas = []
    layers = []

    canvas.append({
        "size": psd.size
    })
        
    for layer in psd:
        layers.append({
            "name": layer.name,
            "left": layer.left,
            "top": layer.top,
            "right": layer.right,
            "bottom": layer.bottom,
            "visible": layer.visible,
            "opacity": layer.opacity,
        })

    return {
        "file": os.path.basename(psd_path),
        "canvas": canvas,
        "layerCount": len(psd),
        "layers": layers
    }

def walk_and_export_json(root_dir, output_base_dir):
    for dirpath, _, filenames in os.walk(root_dir):
        for file in filenames:
            if file.lower().endswith(".psd"):
                full_path = os.path.join(dirpath, file)
                print(f"처리중: {full_path}")

                try:
                    info = extract_layer_info(full_path)

                    # 상대 경로 유지
                    rel_dir = os.path.relpath(dirpath, root_dir)
                    output_dir = os.path.join(output_base_dir, rel_dir)
                    os.makedirs(output_dir, exist_ok=True)

                    # JSON 파일 경로 구성
                    json_name = os.path.splitext(file)[0] + ".json"
                    json_path = os.path.join(output_dir, json_name)

                    with open(json_path, "w", encoding="utf-8") as f:
                        json.dump(info, f, ensure_ascii=False, indent=2)

                except Exception as e:
                    print(f"❌ 오류: {file} - {e}")

if __name__ == "__main__":
    walk_and_export_json(
        root_dir=r".\output\2506\A\TEST",
        output_base_dir=r".\output_json\2506\A\TEST"
    )
