function Get-APImageVideoExtensions {
    param (
        [string] $sourceUrl = "https://cdn.jsdelivr.net/gh/jshttp/mime-db@v1.52.0/db.json"
    )
    $jsonData = (Invoke-RestMethod $sourceUrl).PSObject.Properties
    $extensions = @()

    foreach ($item in $jsonData) {
        if ($item.Name -match "^(image|video)") {
            $extensions += $item.Value.extensions
        }
    }

    $extensions = $extensions | Sort-Object -Unique
    return $extensions
}

function Get-APFileDateTaken {
    param (
        [string] $FilePath
    )
    $Folder = (New-Object -ComObject Shell.Application).NameSpace((Split-Path $FilePath))
    $PropIndex = 12  # Date Taken Property Index
    $CharWhiteList = '[^: \w\/]'

    $DateTaken = $Folder.GetDetailsOf(
        $Folder.ParseName((Split-Path -Leaf $FilePath)),
        $PropIndex
    ) -replace $CharWhiteList

    
    $DateTaken = try { [DateTime]($DateTaken) } catch { $null }
    return $DateTaken
}

function Get-APTemporaryDirectory {
    do {
        $TempDir = Join-Path -Path $env:TEMP -ChildPath ([System.IO.Path]::GetRandomFileName())
    } while (Test-Path $TempDir)
    return $TempDir
}

function Get-APCreationDateSubDirectory {
    param (
        [string] $filePath
    )

    $originalDate = Get-APFileDateTaken -FilePath $filePath

    if ($originalDate) {
        $year = $originalDate.Year
        $month = $originalDate.Month.ToString("D2")
        $monthName = Get-Culture | ForEach-Object { $_.DateTimeFormat.GetMonthName($month) }

        return "$year\$month - $monthName"
    } else {
        return "Non daté"
    }
}

if (-not $args[0] -or -not $args[1]) {
    $SourceDir = Read-Host "Veuillez entrer le chemin du dossier source (ou une archive .zip)"
    $DestinationDir = Read-Host "Veuillez entrer le chemin du dossier destination"
} else {
    $SourceDir = $args[0]
    $DestinationDir = $args[1]
}

if ($SourceDir -imatch "\.zip$") {
    $TempDir = Get-APTemporaryDirectory

    try {
        Expand-Archive -Path $SourceDir -DestinationPath $TempDir
        $SourceDir = $TempDir
    }catch{
        Write-Host "L'archive n'a pas pu être décompressée."
        return
    }
}

$ValidExtensions = Get-APImageVideoExtensions
Get-ChildItem -Path $SourceDir -Recurse -File | ForEach-Object {
    $File = $_
    $FileExtension = $File.Extension.ToLower().TrimStart('.')

    if ($ValidExtensions -contains $FileExtension) {
        $subFolder = Get-APCreationDateSubDirectory -filePath $File.FullName
        $targetDir = Join-Path -Path $DestinationDir -ChildPath $subFolder

        if (-not (Test-Path $targetDir)) {
            New-Item -Path $targetDir -ItemType Directory | Out-Null
        }

        Copy-Item -Path $file.FullName -Destination $targetDir
    } else {
        Write-Host "Fichier ignoré: $($file.FullName)"
    }
}

if ($SourceDir -like "$env:TEMP\*") {
    Remove-Item -Path $SourceDir -Recurse -Force
}