import os
import subprocess
import re
from PIL import Image

SVGS_THREE = {
    # 1. Asistente IA en 2D (Robot amigable con visor iluminado, antena y destellos dorados)
    "icon_asistente_ia": """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
  <defs>
    <filter id="shadow" x="-5%" y="-5%" width="110%" height="115%">
      <feDropShadow dx="0" dy="8" stdDeviation="10" flood-color="#14334F" flood-opacity="0.2"/>
    </filter>
  </defs>
  <g filter="url(#shadow)">
    <!-- AI Sparkles on top -->
    <path d="M120 100 L126 120 L146 126 L126 132 L120 152 L114 132 L94 126 L114 120 Z" fill="#D29C38"/>
    <path d="M380 90 L388 116 L414 124 L388 132 L380 158 L372 132 L346 124 L372 116 Z" fill="#D29C38"/>
    <circle cx="200" cy="70" r="10" fill="#D29C38"/>
    <circle cx="310" cy="65" r="8" fill="#D29C38"/>

    <!-- Antenna -->
    <line x1="256" y1="90" x2="256" y2="150" stroke="#1C4468" stroke-width="16" stroke-linecap="round"/>
    <circle cx="256" cy="74" r="26" fill="#D29C38" stroke="#B37F22" stroke-width="8"/>
    <circle cx="256" cy="74" r="10" fill="#F7F4EC"/>

    <!-- Ear / Audio Modules -->
    <rect x="76" y="240" width="36" height="80" rx="16" fill="#D29C38" stroke="#B37F22" stroke-width="6"/>
    <rect x="400" y="240" width="36" height="80" rx="16" fill="#D29C38" stroke="#B37F22" stroke-width="6"/>

    <!-- Main Robot Head Body -->
    <rect x="96" y="140" width="320" height="280" rx="90" fill="#1C4468" stroke="#14334F" stroke-width="14"/>
    
    <!-- Decorative Neck / Base Collar -->
    <path d="M170 420 L342 420 L320 460 L192 460 Z" fill="#D29C38" stroke="#B37F22" stroke-width="8"/>

    <!-- Screen Visor Face plate -->
    <rect x="136" y="180" width="240" height="200" rx="60" fill="#14334F" stroke="#DCE8F2" stroke-width="10"/>

    <!-- Glowing Friendly Eyes (Gold) -->
    <ellipse cx="206" cy="270" rx="22" ry="32" fill="#D29C38"/>
    <ellipse cx="206" cy="270" rx="12" ry="20" fill="#FFDE59"/>
    <ellipse cx="306" cy="270" rx="22" ry="32" fill="#D29C38"/>
    <ellipse cx="306" cy="270" rx="12" ry="20" fill="#FFDE59"/>

    <!-- Happy Smile -->
    <path d="M228 325 Q256 350 284 325" fill="none" stroke="#D29C38" stroke-width="12" stroke-linecap="round"/>
  </g>
</svg>""",

    # 2. Sede Corporativa en 2D (Edificio empresarial elegante azul y oro)
    "icon_empresa_corp": """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
  <defs>
    <filter id="shadow" x="-5%" y="-5%" width="110%" height="115%">
      <feDropShadow dx="0" dy="8" stdDeviation="10" flood-color="#14334F" flood-opacity="0.2"/>
    </filter>
  </defs>
  <g filter="url(#shadow)">
    <!-- Base pavement -->
    <rect x="70" y="420" width="372" height="30" rx="10" fill="#1C4468" stroke="#14334F" stroke-width="6"/>
    <!-- Main Corporate Tower -->
    <rect x="110" y="100" width="292" height="320" rx="20" fill="#1C4468" stroke="#14334F" stroke-width="12"/>
    <!-- Roof cornice -->
    <rect x="94" y="90" width="324" height="30" rx="8" fill="#D29C38" stroke="#B37F22" stroke-width="6"/>
    <!-- Corporate Entrance Arch / Portico -->
    <rect x="210" y="320" width="92" height="100" rx="12" fill="#D29C38" stroke="#B37F22" stroke-width="8"/>
    <rect x="230" y="350" width="52" height="70" rx="6" fill="#F7F4EC"/>
    <line x1="256" y1="350" x2="256" y2="420" stroke="#1C4468" stroke-width="4"/>
    <!-- Windows Floor 1 -->
    <rect x="146" y="146" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <rect x="229" y="146" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <rect x="312" y="146" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <!-- Windows Floor 2 -->
    <rect x="146" y="206" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <rect x="229" y="206" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <rect x="312" y="206" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <!-- Windows Floor 3 -->
    <rect x="146" y="266" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <rect x="229" y="266" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <rect x="312" y="266" width="54" height="42" rx="8" fill="#DCE8F2"/>
    <!-- Golden antenna / tech beacon -->
    <line x1="256" y1="40" x2="256" y2="90" stroke="#D29C38" stroke-width="10" stroke-linecap="round"/>
    <circle cx="256" cy="40" r="12" fill="#D29C38"/>
  </g>
</svg>""",

    # 3. Series de Facturación en 2D (Archivador de series A, B, C y documento de factura)
    "icon_series_facturacion": """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
  <defs>
    <filter id="shadow" x="-5%" y="-5%" width="110%" height="115%">
      <feDropShadow dx="0" dy="8" stdDeviation="10" flood-color="#14334F" flood-opacity="0.2"/>
    </filter>
  </defs>
  <g filter="url(#shadow)">
    <!-- Back binder / folder -->
    <rect x="90" y="110" width="310" height="340" rx="20" fill="#14334F"/>
    <!-- Folder body -->
    <rect x="106" y="120" width="294" height="330" rx="16" fill="#1C4468" stroke="#14334F" stroke-width="10"/>
    <!-- Sheet with series tabs -->
    <!-- Tab 1 (A) -->
    <rect x="360" y="140" width="70" height="50" rx="8" fill="#D29C38" stroke="#B37F22" stroke-width="4"/>
    <text x="395" y="176" font-family="Arial, sans-serif" font-weight="900" font-size="28" fill="#1C4468" text-anchor="middle">A</text>
    <!-- Tab 2 (B) -->
    <rect x="360" y="210" width="70" height="50" rx="8" fill="#DCE8F2" stroke="#1C4468" stroke-width="4"/>
    <text x="395" y="246" font-family="Arial, sans-serif" font-weight="900" font-size="28" fill="#1C4468" text-anchor="middle">B</text>
    <!-- Tab 3 (C) -->
    <rect x="360" y="280" width="70" height="50" rx="8" fill="#D29C38" stroke="#B37F22" stroke-width="4"/>
    <text x="395" y="316" font-family="Arial, sans-serif" font-weight="900" font-size="28" fill="#1C4468" text-anchor="middle">C</text>
    <!-- Invoice Page in front -->
    <rect x="140" y="150" width="220" height="270" rx="12" fill="#F7F4EC" stroke="#D29C38" stroke-width="8"/>
    <!-- Invoice lines -->
    <rect x="165" y="180" width="130" height="24" rx="6" fill="#1C4468"/>
    <line x1="165" y1="230" x2="330" y2="230" stroke="#1C4468" stroke-width="8" stroke-linecap="round"/>
    <line x1="165" y1="265" x2="310" y2="265" stroke="#1C4468" stroke-width="8" stroke-linecap="round"/>
    <line x1="165" y1="300" x2="280" y2="300" stroke="#D29C38" stroke-width="8" stroke-linecap="round"/>
    <!-- Stamp / seal -->
    <circle cx="290" cy="360" r="32" fill="#D29C38" stroke="#1C4468" stroke-width="6"/>
    <path d="M280 360 L288 368 L302 352" fill="none" stroke="#FFFFFF" stroke-width="6" stroke-linecap="round"/>
  </g>
</svg>"""
}

masters_dir = "resources/iconos_secciones/masters"
icons_dir = "resources/iconos_secciones"
os.makedirs(masters_dir, exist_ok=True)
os.makedirs("scratch/rendered", exist_ok=True)

chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"

print("Rendering 3 2D icons...")
for name, svg in SVGS_THREE.items():
    html_file = f"scratch/rendered/{name}.html"
    master_png = os.path.join(masters_dir, f"{name}.png")
    ui_png = os.path.join(icons_dir, f"{name}.png")
    
    html = f"""<!DOCTYPE html><html><head><style>
body {{ margin: 0; padding: 0; background: transparent; overflow: hidden; }}
svg {{ display: block; width: 512px; height: 512px; }}
</style></head><body>{svg}</body></html>"""
    
    with open(html_file, "w", encoding="utf-8") as f:
        f.write(html)
        
    cmd = [
        chrome_path, "--headless=new", "--disable-gpu",
        "--default-background-color=00000000", "--window-size=512,512",
        f"--screenshot={os.path.abspath(master_png)}",
        f"file:///{os.path.abspath(html_file)}"
    ]
    subprocess.run(cmd, check=True)
    
    # Resize master to 42x42 for UI
    im = Image.open(master_png)
    im42 = im.resize((42, 42), Image.Resampling.LANCZOS)
    im42.save(ui_png)
    print(f"Generated 2D {name}: master and 42x42")

# Now update hex data in dmg_Main.dfm for these 3 items in imgCollection
def format_png_to_dfm_data(png_path):
    with open(png_path, "rb") as f:
        b = f.read()
    hex_str = b.hex().upper()
    lines = []
    for i in range(0, len(hex_str), 66):
        lines.append("              " + hex_str[i:i+66])
    return "\n".join(lines)

with open("src/Data/dmg_Main.dfm", "r", encoding="latin-1") as f:
    dmg_text = f.read()

for name in SVGS_THREE.keys():
    ui_png = os.path.join(icons_dir, f"{name}.png")
    new_hex = format_png_to_dfm_data(ui_png)
    
    # Regex to match the item block for this name in imgCollection
    pattern = rf"(item\s+Name = '{name}'\s+SourceImages = <\s+item\s+Image\.Data = {{\s*)([0-9A-F\s]+)(\s*}}\s+end>)"
    match = re.search(pattern, dmg_text)
    if match:
        dmg_text = dmg_text[:match.start(2)] + new_hex + dmg_text[match.end(2):]
        print(f"Updated hex in dmg_Main.dfm for {name}")
    else:
        print(f"Warning: could not find item block for {name} in dmg_Main.dfm")

with open("src/Data/dmg_Main.dfm", "w", encoding="latin-1") as f:
    f.write(dmg_text)

# Validate with convert.exe
convert_exe = r"C:\Program Files (x86)\Embarcadero\Studio\22.0\bin\convert.exe"
res = subprocess.run([convert_exe, "-t", r"src\Data\dmg_Main.dfm"], capture_output=True, text=True)
if os.path.exists(r"src\Data\dmg_Main.txt"):
    os.remove(r"src\Data\dmg_Main.txt")
    print("convert.exe verified dmg_Main.dfm syntax successfully!")

print("All 3 icons converted to 2D and synced!")
