import sys, os
os.environ.setdefault('PYTHONIOENCODING', 'utf-8')
sys.stdout.reconfigure(encoding='utf-8')

import photoshop.api as ps

PSD = r"d:\pomysloweprezenty.pl\projekty\ślub - zaproszenia\Akrylowe zaproszenie ślubne dla rodziców ze zdjęciem - Wzór 5\Akrylowe zaproszenie ślubne dla rodziców ze zdjęciem - Wzór 5.psd"

app = ps.Application()
doc = app.open(PSD)

def explore(container, indent=0):
    try:
        for al in container.artLayers:
            extra = ''
            try:
                if al.kind == 2:
                    extra = f' TEXT="{al.textItem.contents}"'
                else:
                    extra = f' kind={al.kind}'
            except Exception as e:
                extra = f' (err:{e})'
            print(f'{"  "*indent}- art "{al.name}"{extra}')
    except Exception:
        pass
    try:
        for ls in container.layerSets:
            print(f'{"  "*indent}+ set "{ls.name}"')
            explore(ls, indent+1)
    except Exception:
        pass

print(f'== DOC: {doc.name} ==')
explore(doc)

# wyszukaj smart objecty (kind 5 lub 7) na top-level i wejdz
def find_smart(container, path=''):
    found = []
    try:
        for al in container.artLayers:
            try:
                if al.kind in (5, 7):
                    found.append((path + '/' + al.name, al))
            except: pass
    except: pass
    try:
        for ls in container.layerSets:
            found.extend(find_smart(ls, path + '/' + ls.name))
    except: pass
    return found

smarts = find_smart(doc)
print('\n== SMART OBJECTS ==')
for p, _ in smarts:
    print(p)

# Wejdz do pierwszego SO top-level (zakładamy projekt)
if smarts:
    path, layer = smarts[0]
    print(f'\n== ENTER SO: {path} ==')
    doc.activeLayer = layer
    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)
    so_doc = app.activeDocument
    print(f'SO doc: {so_doc.name}')
    explore(so_doc)
    so_doc.close(ps.SaveOptions.DoNotSaveChanges)

doc.close(ps.SaveOptions.DoNotSaveChanges)
print('\nDONE')
