import os
import subprocess
import datetime
from pathlib import Path


def run(cmd):
    try:
        p = subprocess.run(
            cmd,
            shell=True,
            capture_output=True,
            text=True,
            errors="replace",
            timeout=30,
        )
        return (
            f"> {cmd}\n"
            f"Exit code: {p.returncode}\n"
            + (f"\n--- STDOUT ---\n{p.stdout.strip()}\n" if p.stdout.strip() else "")
            + (f"\n--- STDERR ---\n{p.stderr.strip()}\n" if p.stderr.strip() else "")
        )
    except Exception as e:
        return f"> {cmd}\nERROR: {type(e).__name__}: {e}\n"


def file_check(path):
    p = Path(os.path.expandvars(path))
    try:
        if p.exists():
            st = p.stat()
            return f"{p}\n  exists: yes\n  size: {st.st_size}\n  modified: {datetime.datetime.fromtimestamp(st.st_mtime)}"
        return f"{p}\n  exists: no"
    except Exception as e:
        return f"{p}\n  error: {type(e).__name__}: {e}"


def main():
    lines = []

    def section(title):
        lines.append("\n" + "=" * 90)
        lines.append(title)
        lines.append("=" * 90)

    section("BASIC INFO")
    lines.append(f"Timestamp: {datetime.datetime.now().isoformat(timespec='seconds')}")
    lines.append(f"User: {os.environ.get('USERNAME')}")
    lines.append(f"User profile: {os.environ.get('USERPROFILE')}")
    lines.append(f"LocalAppData: {os.environ.get('LOCALAPPDATA')}")
    lines.append(f"AppData: {os.environ.get('APPDATA')}")

    section("HKCU PNG CLASS OVERRIDES - MOST IMPORTANT")
    lines.append(run(r'reg query "HKCU\Software\Classes\.png" /s'))
    lines.append(run(r'reg query "HKCU\Software\Classes\pngfile" /s'))
    lines.append(run(r'reg query "HKCU\Software\Classes\SystemFileAssociations\.png" /s'))

    section("HKCU PNG FILEEXTS")
    lines.append(run(r'reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.png" /s'))
    lines.append(run(r'reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.png\UserChoice" /s'))

    section("HKCU/HKLM KINDMAP")
    lines.append(run(r'reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\KindMap" /v .png'))
    lines.append(run(r'reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\KindMap" /v .png'))

    section("HKCR PNG EFFECTIVE VIEW")
    lines.append(run(r'reg query "HKCR\.png" /s'))
    lines.append(run(r'reg query "HKCR\pngfile" /s'))
    lines.append(run(r'reg query "HKCR\SystemFileAssociations\.png" /s'))

    section("PNG-RELATED SHELL EXTENSIONS")
    lines.append(run(r'reg query "HKCR\.png\shellex" /s'))
    lines.append(run(r'reg query "HKCR\pngfile\shellex" /s'))
    lines.append(run(r'reg query "HKCR\SystemFileAssociations\.png\shellex" /s'))

    section("IMAGE/PREVIEW/THUMBNAIL HANDLERS")
    lines.append(run(r'reg query "HKCR\CLSID\{E357FCCD-A995-4576-B01F-234630154E96}" /s'))
    lines.append(run(r'reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved" /f "thumbnail" /s'))
    lines.append(run(r'reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions" /s'))

    section("SHELL ICON / OVERLAY OVERRIDES")
    lines.append(run(r'reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Icons" /s'))
    lines.append(run(r'reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Icons" /s'))
    lines.append(run(r'reg query "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers" /s'))
    lines.append(run(r'reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers" /s'))

    section("TEST ICON FILES")
    test_paths = [
        r"%USERPROFILE%\Desktop\test-icon.png",
        r"C:\Program Files\WindowsApps\Microsoft.WindowsNotepad_11.2604.5.0_x64__8wekyb3d8bbwe\Assets\txtfile.targetsize-256.png",
        r"C:\Program Files\WindowsApps\Microsoft.WindowsNotepad_11.2604.5.0_x64__8wekyb3d8bbwe\Assets\txtfile.targetsize-64.png",
        r"C:\Program Files\WindowsApps\Microsoft.WindowsNotepad_11.2604.5.0_neutral_split.scale-100_8wekyb3d8bbwe\Assets\NotepadAppList.scale-100.png",
    ]
    for path in test_paths:
        lines.append(file_check(path))

    section("DESKTOP TEST SHORTCUTS")
    desktop = Path(os.environ.get("USERPROFILE", "")) / "Desktop"
    for name in [
        "Icon Test - Notepad PNG.lnk",
        "Icon Test - Desktop PNG.lnk",
        "Icon Test - Shell32.lnk",
        "Icon Test - ICO.lnk",
    ]:
        lines.append(file_check(str(desktop / name)))

    section("EXPLORER CACHE FILES")
    explorer_cache = Path(os.environ.get("LOCALAPPDATA", "")) / "Microsoft" / "Windows" / "Explorer"
    lines.append(f"Explorer cache folder: {explorer_cache}")
    if explorer_cache.exists():
        for p in sorted(explorer_cache.glob("*")):
            if "iconcache" in p.name.lower() or "thumbcache" in p.name.lower():
                try:
                    st = p.stat()
                    lines.append(
                        f"{p.name:45} size={st.st_size:12} modified={datetime.datetime.fromtimestamp(st.st_mtime)}"
                    )
                except Exception as e:
                    lines.append(f"{p.name:45} error={e}")
    else:
        lines.append("Explorer cache folder does not exist.")

    section("CACHE ACLS")
    lines.append(run(fr'icacls "{explorer_cache}"'))
    lines.append(run(fr'icacls "{explorer_cache}\iconcache*"'))
    lines.append(run(fr'icacls "{explorer_cache}\thumbcache*"'))

    out = Path.cwd() / f"png_icon_debug_REPORT_{datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')}.txt"
    out.write_text("\n".join(lines), encoding="utf-8", errors="replace")

    print("Report written to:")
    print(out)


if __name__ == "__main__":
    if os.name != "nt":
        raise SystemExit("This script is for Windows only.")
    main()