$projectRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
$logsDir = Join-Path $projectRoot "logs"
$sessionsDir = Join-Path $logsDir "sessions"
$agentsDir = Join-Path $logsDir "agents"
$errorsDir = Join-Path $logsDir "errors"
$testsDir = Join-Path $projectRoot "tests"
$artifactsDir = Join-Path $testsDir "artifacts"

# Ensure target directories exist
New-Item -ItemType Directory -Force -Path $sessionsDir | Out-Null
New-Item -ItemType Directory -Force -Path $agentsDir | Out-Null
New-Item -ItemType Directory -Force -Path $errorsDir | Out-Null
New-Item -ItemType Directory -Force -Path $artifactsDir | Out-Null

Write-Host "Migrating logs and temporary files to new taxonomy..."

# 1. Move temp files
Get-ChildItem -Path $projectRoot -Filter "temp_*" -File | ForEach-Object {
    Write-Host "Moving $($_.Name) to tests/artifacts/"
    Move-Item -Path $_.FullName -Destination $artifactsDir -Force
}
if (Test-Path $testsDir) {
    Get-ChildItem -Path $testsDir -Filter "temp_*" -File | ForEach-Object {
        Write-Host "Moving $($_.Name) to tests/artifacts/"
        Move-Item -Path $_.FullName -Destination $artifactsDir -Force
    }
}

# 2. Move MMA logs to logs/agents/
Get-ChildItem -Path $logsDir -Filter "mma_*.log" -File | ForEach-Object {
    Write-Host "Moving $($_.Name) to logs/agents/"
    Move-Item -Path $_.FullName -Destination $agentsDir -Force
}

# 3. Move error/test logs to logs/errors/
Get-ChildItem -Path $logsDir -Filter "*.log" -File | Where-Object { $_.Name -like "*test*" -or $_.Name -like "gui_*.log" } | ForEach-Object {
    Write-Host "Moving $($_.Name) to logs/errors/"
    Move-Item -Path $_.FullName -Destination $errorsDir -Force
}

# 4. Move log_registry.toml to logs/sessions/
if (Test-Path (Join-Path $logsDir "log_registry.toml")) {
    Write-Host "Moving log_registry.toml to logs/sessions/"
    Move-Item -Path (Join-Path $logsDir "log_registry.toml") -Destination $sessionsDir -Force
}

# 5. Move session directories to logs/sessions/
# Pattern: Starts with 202 (year)
Get-ChildItem -Path $logsDir -Directory | Where-Object { $_.Name -match "^202\d" } | ForEach-Object {
    Write-Host "Moving session directory $($_.Name) to logs/sessions/"
    Move-Item -Path $_.FullName -Destination $sessionsDir -Force
}

# 6. Move remaining .log files to logs/sessions/
Get-ChildItem -Path $logsDir -Filter "*.log" -File | ForEach-Object {
    Write-Host "Moving session log $($_.Name) to logs/sessions/"
    Move-Item -Path $_.FullName -Destination $sessionsDir -Force
}

Write-Host "Migration complete."
