#!/usr/bin/env nu
# Rustelo Cache Manager - PAP-compliant cache management
# Provides comprehensive cache inspection, cleaning, and management

# Get cache paths from manifest configuration
def get_cache_paths [] {
    let workspace_root = (pwd)
    let cache_build_path = "site_build/devtools/build-cache"  # From manifest
    let build_cache_root = ($workspace_root | path join "target" $cache_build_path)

    {
        workspace: $workspace_root,
        build_root: $build_cache_root,
        client: ($build_cache_root | path join "client"),
        server: ($build_cache_root | path join "server"),
        docs: ($workspace_root | path join "site" "info"),
        deployment: ($workspace_root | path join "cache"),
        node: ($workspace_root | path join "node_modules" ".cache")
    }
}

# Show cache status and sizes
def "cache status" [] {
    let paths = (get_cache_paths)

    print "🗄️  Rustelo Cache Status (PAP-compliant)"
    print "========================================"
    print ""
    print "📁 Cache Directories:"

    # Check each cache directory
    for cache_type in ["client", "server", "docs", "deployment", "node"] {
        let path = ($paths | get $cache_type)
        if ($path | path exists) {
            let size = (du $path | get apparent | math sum | into string --decimals=1 | $in + "B")
            print $"✅ (($cache_type | str capitalize)) cache: ($size) \(($path)\)"
        } else {
            print $"❌ (($cache_type | str capitalize)) cache: Not found \(($path)\)"
        }
    }

    print ""
    print "📄 Cache Files:"

    # Count cache files by type
    if ($paths.client | path exists) {
        let client_files = (try { ls $paths.client -a | where type == "file" } | default [])
        let css_count = ($client_files | where name =~ '\.css$' | length)
        let meta_count = ($client_files | where name =~ '\.json$' | length)
        print $"  CSS cache: ($css_count) files"
        print $"  Meta files: ($meta_count) files"
    }

    if ($paths.server | path exists) {
        let server_files = (try { ls $paths.server -a | where type == "file" } | default [])
        let route_count = ($server_files | where name =~ 'routes_.*\.cache$' | length)
        let metadata_count = ($server_files | where name =~ 'metadata_.*\.cache$' | length)
        print $"  Route cache: ($route_count) files"
        print $"  Metadata cache: ($metadata_count) files"
    }

    if ($paths.docs | path exists) {
        let doc_files = (try { ls $paths.docs -a | where type == "file" } | default [])
        let md_count = ($doc_files | where name =~ '\.md$' | length)
        let toml_count = ($doc_files | where name =~ '\.toml$' | length)
        print $"  Documentation: ($md_count) markdown, ($toml_count) data files"
    }
}

# List all cache files with details
def "cache list" [] {
    let paths = (get_cache_paths)

    print "📋 Cache File Details (PAP-compliant)"
    print "====================================="
    print ""

    if ($paths.build_root | path exists) or ($paths.docs | path exists) {
        let client_files = (try { ls $paths.client -a -l | where type == "file" } | default [])
        let server_files = (try { ls $paths.server -a -l | where type == "file" } | default [])
        let doc_files = (try { ls $paths.docs -a -l | where type == "file" } | default [])
        let all_cache_files = ($client_files | append $server_files | append $doc_files
                               | where name =~ '\.(cache|css|json|md|toml)$'
                               | select name size modified
                               | sort-by size -r)

        if ($all_cache_files | length) > 0 {
            $all_cache_files
        } else {
            print "ℹ️  No cache files found"
        }
    } else {
        print $"❌ No cache directory found at: ($paths.build_root)"
    }
}

# Show cache statistics by type
def "cache stats" [] {
    let paths = (get_cache_paths)

    print "📊 Cache Statistics (PAP-compliant)"
    print "==================================="
    print ""

    # CSS Cache stats
    if ($paths.client | path exists) {
        let css_files = (try { ls ($paths.client | path join "*") -a | where type == "file" and name =~ '\.css$' } | default [])
        let css_size = (if ($css_files | length) > 0 { $css_files | get size | math sum } else { 0 })
        print "🎨 CSS Cache:"
        print $"  Files: ($css_files | length)"
        print $"  Size:  ($css_size | into string --decimals=1)B"
        print ""
    }

    # Server Cache stats
    if ($paths.server | path exists) {
        let route_files = (try { ls ($paths.server | path join "routes_*.cache") -a | where type == "file" } | default [])
        let route_size = (if ($route_files | length) > 0 { $route_files | get size | math sum } else { 0 })
        print "🛣️  Route Cache:"
        print $"  Files: ($route_files | length)"
        print $"  Size:  ($route_size | into string --decimals=1)B"
        print ""

        let metadata_files = (try { ls ($paths.server | path join "metadata_*.cache") -a | where type == "file" } | default [])
        let metadata_size = (if ($metadata_files | length) > 0 { $metadata_files | get size | math sum } else { 0 })
        print "📋 Metadata Cache:"
        print $"  Files: ($metadata_files | length)"
        print $"  Size:  ($metadata_size | into string --decimals=1)B"
        print ""
    }

    # Documentation Cache stats
    if ($paths.docs | path exists) {
        let doc_files = (try { ls ($paths.docs | path join "*") -a | where type == "file" } | default [])
        let doc_size = (if ($doc_files | length) > 0 { $doc_files | get size | math sum } else { 0 })
        let md_files = ($doc_files | where name =~ '\.md$')
        let toml_files = ($doc_files | where name =~ '\.toml$')
        print "📚 Documentation Cache:"
        print $"  Markdown files: ($md_files | length)"
        print $"  Data files: ($toml_files | length)"
        print $"  Total size: ($doc_size | into string --decimals=1)B"
    }
}

# Clean specific cache types
def "cache clean" [
    cache_type: string  # Cache type to clean: client|server|routes|pages|docs|css|js|all|rustelo
] {
    let paths = (get_cache_paths)

    match $cache_type {
        "client" => {
            if ($paths.client | path exists) {
                rm -rf $paths.client
                print $"✅ Cleaned client cache: ($paths.client)"
            } else {
                print $"ℹ️  No client cache to clean"
            }
        },
        "server" => {
            if ($paths.server | path exists) {
                rm -rf $paths.server
                print $"✅ Cleaned server cache: ($paths.server)"
            } else {
                print $"ℹ️  No server cache to clean"
            }
        },
        "css" => {
            if ($paths.client | path exists) {
                try {
                    ls ($paths.client | path join "*") -a
                        | where name =~ '\.(css|styles)'
                        | each { |file| rm $file.name }
                }
                print "✅ Cleaned CSS cache files"
            } else {
                print "ℹ️  No CSS cache to clean"
            }
        },
        "routes" => {
            if ($paths.server | path exists) {
                try {
                    ls ($paths.server | path join "routes_*.cache") -a
                        | each { |file| rm $file.name }
                }
                print "✅ Cleaned route cache files"
            } else {
                print "ℹ️  No route cache to clean"
            }
        },
        "pages" => {
            if ($paths.server | path exists) {
                try {
                    ls ($paths.server | path join "metadata_*.cache") -a
                        | each { |file| rm $file.name }
                }
                print "✅ Cleaned page metadata cache files"
            } else {
                print "ℹ️  No page metadata cache to clean"
            }
        },
        "docs" => {
            if ($paths.docs | path exists) {
                rm -rf $paths.docs
                print $"✅ Cleaned documentation cache: ($paths.docs)"
            } else {
                print $"ℹ️  No documentation cache to clean"
            }
        },
        "js" => {
            if ($paths.node | path exists) {
                rm -rf $paths.node
                print $"✅ Cleaned Node.js cache: ($paths.node)"
            }
            if ($paths.workspace | path join "package-lock.json" | path exists) {
                rm ($paths.workspace | path join "package-lock.json")
                print "✅ Removed package-lock.json"
            }
            print "✅ JavaScript caches cleaned"
        },
        "rustelo" => {
            if ($paths.build_root | path exists) {
                rm -rf $paths.build_root
                print $"✅ Cleaned Rustelo build cache: ($paths.build_root)"
            } else {
                print $"ℹ️  No Rustelo cache to clean"
            }
        },
        "all" => {
            # Clean all cache types
            for type in ["rustelo", "docs", "js"] {
                cache clean $type
            }
            # Clean cargo cache
            run-external "cargo" "clean"
            print "✅ Cargo cache cleaned"
            print "🧹 All caches cleaned!"
        },
        _ => {
            error make {msg: $"Unknown cache type: ($cache_type). Use: client|server|routes|pages|docs|css|js|rustelo|all"}
        }
    }
}

# Force regenerate specific cache types
def "cache force" [
    cache_type: string  # Cache type to force regenerate: css|routes|pages|docs
] {
    match $cache_type {
        "css" => {
            print "🔄 Force regenerating CSS..."
            cache clean css
            run-external "npm" "run" "css:build"
            print "✅ CSS cache regenerated"
        },
        "routes" => {
            print "🔄 Force regenerating routes..."
            cache clean routes
            run-external "cargo" "build"
            print "✅ Route cache regenerated"
        },
        "pages" => {
            print "🔄 Force regenerating page metadata..."
            cache clean pages
            run-external "cargo" "build"
            print "✅ Page metadata cache regenerated"
        },
        "docs" => {
            print "🔄 Force regenerating documentation..."
            cache clean docs
            # Use available documentation build commands
            run-external "just" "docs::info-generate"
            run-external "just" "tools::tools-analyze"
            print "✅ Documentation cache regenerated"
        },
        _ => {
            error make {msg: $"Unknown cache type: ($cache_type). Use: css|routes|pages|docs"}
        }
    }
}

# Clean old cache files (older than specified days)
def "cache clean-old" [
    days: int = 7  # Number of days (default: 7)
] {
    let paths = (get_cache_paths)
    let cutoff_date = ((date now) - ($days | into duration --unit day))

    print $"⏰ Cleaning cache files older than ($days) days..."

    if ($paths.build_root | path exists) {
        let old_files = (ls $paths.build_root -a -l
            | where modified < $cutoff_date
            | where type == "file")

        for file in $old_files {
            rm $file.name
        }

        print $"✅ Removed ($old_files | length) old cache files"
    } else {
        print "ℹ️  No cache directory found"
    }
}

# Get cache path for specific type
def "cache path" [
    cache_type: string = "build"  # Cache type: client|server|docs|build|deployment
] {
    let paths = (get_cache_paths)

    match $cache_type {
        "client" => $paths.client,
        "server" => $paths.server,
        "docs" => $paths.docs,
        "build" => $paths.build_root,
        "deployment" => $paths.deployment,
        _ => {
            error make {msg: $"Unknown cache type: ($cache_type). Use: client|server|docs|build|deployment"}
        }
    }
}

# Main command dispatcher
def main [
    command?: string = "help",  # Command to run
    ...args                     # Additional arguments
] {
    match $command {
        "cache" => {
            let subcommand = ($args | get 0? | default "help")
            match $subcommand {
                "status" => { cache status },
                "list" => { cache list },
                "stats" => { cache stats },
                "clean" => {
                    let cache_type = ($args | get 1? | default "all")
                    cache clean $cache_type
                },
                "force" => {
                    let cache_type = ($args | get 1? | default "css")
                    cache force $cache_type
                },
                "clean-old" => {
                    let days = ($args | get 1? | default 7 | into int)
                    cache clean-old $days
                },
                "path" => {
                    let cache_type = ($args | get 1? | default "build")
                    cache path $cache_type
                },
                _ => { show_help }
            }
        },
        "help" | _ => { show_help }
    }
}

# Show help information
def show_help [] {
    print "Rustelo Cache Manager - PAP-compliant cache management"
    print ""
    print "Usage: nu scripts/cache-manager.nu <command> [args...]"
    print ""
    print "Commands:"
    print "  cache status          - Show cache status and sizes"
    print "  cache list            - List all cache files with details"
    print "  cache stats           - Show detailed cache statistics"
    print "  cache clean <type>    - Clean specific cache (client|server|routes|pages|docs|css|js|rustelo|all)"
    print "  cache force <type>    - Force regenerate cache (css|routes|pages|docs)"
    print "  cache clean-old [days] - Clean cache files older than N days (default: 7)"
    print "  cache path <type>     - Get cache path (client|server|docs|build|deployment)"
    print ""
    print "Examples:"
    print "  nu scripts/cache-manager.nu cache status"
    print "  nu scripts/cache-manager.nu cache clean css"
    print "  nu scripts/cache-manager.nu cache force routes"
}
