import os
import re
import hashlib

folder = r'C:\fuentes\proyectos delphi\ICONOS\raul\iconos'

# Read dmg_Main.dfm
with open('src/Data/dmg_Main.dfm', 'r', encoding='latin1') as f:
    text = f.read()

col_match = re.search(r'object imgCollection: TImageCollection(.*?)object imgListRibbon:', text, re.DOTALL)
assert col_match

# Find each item block in imgCollection
# Pattern matches:
# item\s+Name = '([^']*)'\s+SourceImages = <\s+item\s+Image.Data = {([0-9A-Fa-f\s\r\n]+)}\s+end>\s+end
pattern = re.compile(r"item\s+Name = '([^']*)'\s+SourceImages = <\s+item\s+Image\.Data = \{([0-9A-Fa-f\s\r\n]+)\}\s+end>\s+end", re.DOTALL)

matches = list(pattern.finditer(col_match.group(1)))
print(f"Total item blocks matched via regex: {len(matches)}")

# Map each item by its MD5
dmg_items = []
for m in matches:
    name = m.group(1)
    hex_data = re.sub(r'\s+', '', m.group(2))
    raw_data = bytes.fromhex(hex_data)
    md5 = hashlib.md5(raw_data).hexdigest()
    dmg_items.append({
        'name': name,
        'md5': md5,
        'span': (col_match.start(1) + m.start(), col_match.start(1) + m.end()),
        'size': len(raw_data)
    })

# Now check against folder
folder_files = {}
for f in os.listdir(folder):
    if f.lower().endswith('.png'):
        p = os.path.join(folder, f)
        with open(p, 'rb') as fp:
            d = fp.read()
        md5 = hashlib.md5(d).hexdigest()
        folder_files[md5] = f

matched_items = []
unmatched_items = []

for it in dmg_items:
    if it['md5'] in folder_files:
        it['folder_file'] = folder_files[it['md5']]
        matched_items.append(it)
    else:
        unmatched_items.append(it)

print(f"Matched dmg items: {len(matched_items)}")
print(f"Unmatched dmg items: {len(unmatched_items)}")
print("\nFirst 10 matched:")
for m in matched_items[:10]:
    print(f"  ColName: '{m['name']}' -> File: '{m['folder_file']}'")

print("\nSample unmatched dmg items:")
for u in unmatched_items[:10]:
    print(f"  ColName: '{u['name']}'")
