"""Inspekcja PSD: wejscie do kazdego SO i wypisanie jego warstw."""
import os
import subprocess
import time
import photoshop.api as ps

PSD = r"d:\pomysloweprezenty.pl\projekty\buteleczki - indywidualny wzór\Klaudia Buczma.psd"

PHOTOSHOP_EXE_CANDIDATES = [
    r"C:\Program Files\Adobe\Adobe Photoshop 2024\Photoshop.exe",
    r"C:\Program Files\Adobe\Adobe Photoshop 2023\Photoshop.exe",
    r"C:\Program Files\Adobe\Adobe Photoshop 2025\Photoshop.exe",
    r"C:\Program Files\Adobe\Adobe Photoshop 2026\Photoshop.exe",
]


def ensure_photoshop():
    try:
        return ps.Application()
    except Exception:
        for exe in PHOTOSHOP_EXE_CANDIDATES:
            if os.path.exists(exe):
                subprocess.Popen([exe])
                break
        for _ in range(30):
            time.sleep(2)
            try:
                return ps.Application()
            except Exception:
                continue
        raise RuntimeError("brak PS")


def open_smart_object(app):
    desc = ps.ActionDescriptor()
    ref = ps.ActionReference()
    ref.putEnumerated(
        app.stringIDToTypeID("layer"),
        app.stringIDToTypeID("ordinal"),
        app.stringIDToTypeID("targetEnum"),
    )
    desc.putReference(app.stringIDToTypeID("null"), ref)
    app.executeAction(app.stringIDToTypeID("placedLayerEditContents"), desc)


def walk(layer, prefix=""):
    try:
        name = layer.name
    except Exception:
        name = "?"
    kind = type(layer).__name__
    extra = ""
    try:
        if hasattr(layer, "kind"):
            extra = f" kind={layer.kind}"
    except Exception:
        pass
    try:
        bounds = [float(b) for b in layer.bounds]
        extra += f" bounds={bounds}"
    except Exception:
        pass
    content = ""
    try:
        if hasattr(layer, "textItem"):
            content = f"  text=\"{layer.textItem.contents}\""
    except Exception:
        pass
    print(f"{prefix}- {name} [{kind}]{extra}{content}")
    for attr in ("layerSets", "artLayers"):
        try:
            for c in getattr(layer, attr):
                walk(c, prefix + "  ")
        except Exception:
            pass


def dump_doc(doc, label):
    print(f"=== {label}: {doc.name} ===")
    for ls in doc.layerSets:
        walk(ls, "")
    for al in doc.artLayers:
        walk(al, "")


def main():
    app = ensure_photoshop()
    doc = app.open(PSD)
    dump_doc(doc, "ROOT")

    so_names = ["Warstwa 2", "Warstwa 2 kopia", "Warstwa 2 kopia 2", "Warstwa 2 kopia 3"]
    for so_name in so_names:
        try:
            target = doc.artLayers[so_name]
        except Exception:
            print(f"!! brak warstwy {so_name}")
            continue
        doc.activeLayer = target
        try:
            open_smart_object(app)
        except Exception as e:
            print(f"!! nie udalo sie wejsc do {so_name}: {e}")
            continue
        so_doc = app.activeDocument
        dump_doc(so_doc, f"SO[{so_name}]")
        so_doc.close(ps.SaveOptions.DoNotSaveChanges)

    doc.close(ps.SaveOptions.DoNotSaveChanges)


if __name__ == "__main__":
    main()
