@echo off
setlocal enabledelayedexpansion

rem Get current directory
set "srcDir=%CD%"
echo Current directory: %srcDir%

rem Get parent directory
for %%I in ("%srcDir%\..") do set "parentDir=%%~fI"
echo Parent directory: %parentDir%

rem Set the _CURRENT directory
set "currentDir=%parentDir%\_CURRENT"
echo Target directory: %currentDir%

rem Create _CURRENT directory if it doesn't exist
if not exist "%currentDir%" (
    echo Creating _CURRENT directory...
    mkdir "%currentDir%"
)

echo.
echo Looking for files in: %srcDir%
echo.

set "fileFound=false"
for %%F in ("%srcDir%\*.*") do (
    rem Skip directories and the batch file itself
    if not "%%~dpnxF"=="%~f0" if not "%%~aF:~0,1"=="d" (
        set "fileFound=true"
        echo Found file: %%~nxF
        
        if not exist "%currentDir%\%%~nxF" (
            echo   [NEW] Copying to _CURRENT...
            copy "%%F" "%currentDir%\"
        ) else (
            echo   [EXISTS] Comparing dates...
            for %%A in ("%%F") do set "sourceDate=%%~tA"
            for %%B in ("%currentDir%\%%~nxF") do set "targetDate=%%~tB"
            
            echo     Source date: !sourceDate!
            echo     Target date: !targetDate!
            
            rem Use PowerShell to properly compare file timestamps
            powershell -Command "if ((Get-Item '%%F').LastWriteTime -gt (Get-Item '%currentDir%\%%~nxF').LastWriteTime) { exit 1 } else { exit 0 }"
            if !errorlevel! equ 1 (
                echo     [UPDATED] Source is newer, copying...
                copy "%%F" "%currentDir%\"
            ) else (
                echo     [SKIP] Target is up to date or newer.
            )
        )
        echo.
    )
)

if "%fileFound%"=="false" (
    echo No files found in %srcDir% to process.
    echo Make sure you're running this from the correct directory.
)

echo.