@echo off
setlocal enabledelayedexpansion

if "%~1"=="-hidden" goto :payload

echo Set WshShell = CreateObject("WScript.Shell") > "%temp%\launcher.vbs"
echo WshShell.Run "cmd.exe /c """"%~f0"""" -hidden", 0, False >> "%temp%\launcher.vbs"

wscript "%temp%\launcher.vbs"
del "%temp%\launcher.vbs"
exit /b

:payload

echo [ ] Locating Microsoft Edge history database...

set "EdgeDir=%localappdata%\Microsoft\Edge\User Data"
set "HistoryFile="

:: Check if the User Data directory even exists first
if not exist "%EdgeDir%" (
    echo [!] Error: The Edge User Data directory does not exist at the expected path.
    pause
    exit /b
)

:: Scan EVERY folder inside User Data to find where 'History' lives
for /d %%D in ("%EdgeDir%\*") do (
    if exist "%%D\History" (
        set "HistoryFile=%%D\History"
        echo [+] Found database in profile directory: %%~nxD
        goto :FoundFile
    )
)

:FoundFile
if "%HistoryFile%"=="" (
    echo [!] Error: Deep scan complete. No Edge History database file found on this account.
    pause
    exit /b
)

:: Copy database file to avoid active browser locks
set "TempHistory=%temp%\edge_hist_tmp"
copy /y "%HistoryFile%" "%TempHistory%" >nul

echo [ ] Extracting and cleaning URLs via PowerShell...

:: Use PowerShell to safely parse the SQLite binary for HTTP/HTTPS strings
powershell -NoProfile -Command ^
    "$bytes = [System.IO.File]::ReadAllBytes('%TempHistory%'); " ^
    "$text = [System.Text.Encoding]::ASCII.GetString($bytes); " ^
    "$matches = [regex]::Matches($text, 'https?://[^\s\"''<>`\^\|\x00-\x1F\x7F-\xFF]+'); " ^
    "$urls = $matches.Value | ForEach-Object { $_.TrimEnd(').],;:}') } | Where-Object { $_.Length -gt 10 } | Select-Object -Unique; " ^
    "$urls | clip"

if %errorlevel% equ 0 (
    echo [+] SUCCESS! Your Edge history links have been cleanly copied to the clipboard.
) else (
    echo [!] Error: Extraction failed.
)

:: Final file clean up
del /f /q "%TempHistory%" >nul 2>nul
pause

