#!/usr/bin/env nu

# Rustelo Feature Architecture Migration Script
# Migrates p-jpl-website crates to rustelo foundation with proper dependency management

const P_JPL_PATH = "../p-jpl-website"
const FOUNDATION_PATH = "foundation/crates"
const REGISTRY_PATH = "registry"

def main [] {
    print "🚀 Starting Rustelo Feature Architecture Migration"
    print "📋 Phase 1: Foundation Crate Migration"

    # Ensure directories exist
    mkdir $FOUNDATION_PATH
    mkdir $REGISTRY_PATH

    # Step 1: Copy advanced crates from p-jpl-website
    copy_foundation_crates

    # Step 2: Create dependency registry with p-jpl-website priority
    let merged_deps = (create_dependency_registry)

    # Step 3: Update workspace Cargo.toml
    update_workspace_config $merged_deps

    # Step 4: Verify migration
    verify_migration

    print "✅ Migration completed successfully!"
}

def copy_foundation_crates [] {
    print "📦 Copying foundation crates from p-jpl-website..."

    # Core foundation crates (replaces basic rustelo crates)
    let crates_to_copy = [
        "client",      # Advanced Leptos client (replaces basic client)
        "server",      # Advanced Axum server (replaces basic server)
        "core-lib",    # Advanced shared library (replaces shared)
        "core-types"   # Shared types (replaces shared types)
    ]

    for $crate in $crates_to_copy {
        let source_path = $"($P_JPL_PATH)/crates/($crate)"
        let dest_path = $"($FOUNDATION_PATH)/($crate)"

        if ($source_path | path exists) {
            print $"  → Copying ($crate)..."
            cp -r $source_path $dest_path

            # Update internal path dependencies to reflect new structure
            update_crate_dependencies $dest_path
        } else {
            print $"  ⚠️  Warning: ($crate) not found in p-jpl-website"
        }
    }
}

def create_dependency_registry [] {
    print "📋 Creating dependency registry with p-jpl-website priority..."

    # Parse p-jpl-website Cargo.toml
    let p_jpl_cargo = (open $"($P_JPL_PATH)/Cargo.toml")
    let p_jpl_deps = $p_jpl_cargo.workspace.dependencies

    # Parse current rustelo Cargo.toml
    let rustelo_cargo = (open "Cargo.toml")
    let rustelo_deps = $rustelo_cargo.workspace.dependencies

    # Merge dependencies with p-jpl-website priority
    let merged_deps = ($p_jpl_deps | merge $rustelo_deps)

    # Create registry dependencies structure
    let registry_content = {
        dependencies: $merged_deps
    }

    # Convert to TOML format and save
    $registry_content | to toml | save --force $"($REGISTRY_PATH)/dependencies.toml"

    print "  ✓ Dependencies registry created with p-jpl-website priority"

    # Return merged deps for workspace update
    $merged_deps
}

def update_crate_dependencies [crate_path: string] {
    let cargo_path = $"($crate_path)/Cargo.toml"

    if ($cargo_path | path exists) {
        # Read current Cargo.toml
        let cargo_content = (open $cargo_path)

        # Update path dependencies to reflect new structure
        let updated_cargo = (
            $cargo_content
            | upsert dependencies.core-lib { path: "../core-lib" }
            | upsert dependencies.core-types { path: "../core-types" }
            | upsert dependencies.client { path: "../client" }
            | upsert dependencies.server { path: "../server" }
        )

        # Save updated Cargo.toml
        $updated_cargo | to toml | save --force $cargo_path
        print $"    ✓ Updated dependencies in ($crate_path)"
    }
}

def update_workspace_config [merged_deps: record] {
    print "🔧 Updating workspace configuration..."

    # Read current workspace Cargo.toml
    let cargo_content = (open "Cargo.toml")

    # Update workspace members to point to foundation
    let updated_members = [
        # Framework crates
        "framework/crates/rustelo-core",
        "framework/crates/rustelo-web",
        "framework/crates/rustelo-auth",
        "framework/crates/rustelo-content",
        "framework/crates/rustelo-cli",
        # Foundation crates (from p-jpl-website)
        "foundation/crates/client",
        "foundation/crates/server",
        "foundation/crates/core-lib",
        "foundation/crates/core-types"
    ]

    # Update workspace with new structure and dependencies
    let updated_cargo = (
        $cargo_content
        | upsert workspace.members $updated_members
        | upsert workspace.dependencies $merged_deps
        | upsert workspace.dependencies.core-lib { path: "foundation/crates/core-lib" }
        | upsert workspace.dependencies.core-types { path: "foundation/crates/core-types" }
        | upsert workspace.dependencies.client { path: "foundation/crates/client" }
        | upsert workspace.dependencies.server { path: "foundation/crates/server" }
    )

    # Save updated workspace Cargo.toml
    $updated_cargo | to toml | save --force "Cargo.toml"

    print "  ✓ Workspace configuration updated"
}

def verify_migration [] {
    print "🔍 Verifying migration..."

    # Check that foundation crates exist
    let expected_crates = ["client", "server", "core-lib", "core-types"]

    for $crate in $expected_crates {
        let crate_path = $"($FOUNDATION_PATH)/($crate)"
        if ($crate_path | path exists) {
            print $"  ✓ ($crate) migrated successfully"
        } else {
            print $"  ❌ ($crate) migration failed"
        }
    }

    # Verify Cargo.toml syntax
    try {
        cargo check --workspace --all-targets
        print "  ✓ Workspace Cargo.toml syntax valid"
    } catch {
        print "  ⚠️  Workspace Cargo.toml needs manual fixes"
    }

    # Check dependency registry
    if ($"($REGISTRY_PATH)/dependencies.toml" | path exists) {
        print "  ✓ Dependency registry created"
    } else {
        print "  ❌ Dependency registry missing"
    }
}

# Feature extraction functions (Phase 2)

def extract_analytics_feature [] {
    print "📊 Extracting analytics feature from p-jpl-website..."

    let feature_dir = "features/analytics"
    mkdir $feature_dir

    # Copy analytics tools
    let source_tools = $"($P_JPL_PATH)/crates/tools/src/analytics"
    if ($source_tools | path exists) {
        cp -r $source_tools $"($feature_dir)/src"
        print "  ✓ Analytics source copied"
    }

    # Create feature manifest
    create_feature_manifest "analytics" {
        name: "analytics"
        version: "0.1.0"
        source: "p-jpl-website"
        description: "Comprehensive analytics system with navigation tracking, server monitoring, and browser analytics"
        dependencies: {
            workspace: ["chrono", "serde_json", "prometheus"]
            external: ["ratatui = '0.29'", "inquire = '0.7'", "crossterm = '0.29'"]
        }
        environment: [
            {name: "ANALYTICS_ENABLED", default: "true", required: false}
            {name: "ANALYTICS_LOG_PATH", default: "logs/analytics", required: false}
        ]
        scripts: [
            {from: "scripts/analytics", to: "scripts/analytics"}
        ]
    }
}

def extract_smart_build_feature [] {
    print "🔧 Extracting smart-build feature from p-jpl-website..."

    let feature_dir = "features/smart-build"
    mkdir $feature_dir

    # Copy build tools
    let source_build = $"($P_JPL_PATH)/crates/tools/src/build"
    if ($source_build | path exists) {
        cp -r $source_build $"($feature_dir)/src"
        print "  ✓ Smart-build source copied"
    }

    # Create feature manifest
    create_feature_manifest "smart-build" {
        name: "smart-build"
        version: "0.1.0"
        source: "p-jpl-website"
        description: "Incremental build system with intelligent caching"
        dependencies: {
            workspace: ["notify", "lru", "futures"]
            external: []
        }
        environment: [
            {name: "SMART_BUILD_CACHE_DIR", default: ".cache/smart-build", required: false}
            {name: "SMART_BUILD_PARALLEL_JOBS", default: "auto", required: false}
        ]
    }
}

def create_feature_manifest [name: string, config: record] {
    let manifest_path = $"features/($name)/feature.toml"

    let manifest_content = {
        feature: {
            name: $config.name
            version: $config.version
            source: $config.source
            description: $config.description
        }
        dependencies: $config.dependencies
        environment: {
            variables: $config.environment
        }
    }

    $manifest_content | to toml | save --force $manifest_path
    print $"  ✓ Feature manifest created: ($manifest_path)"
}

# Create features registry
def create_features_registry [] {
    print "📋 Creating features registry..."

    let features_registry = [
        "# Rustelo Features Registry"
        ""
        "[features]"
        ""
        "[features.analytics]"
        "description = \"Comprehensive analytics system\""
        "source = \"p-jpl-website\""
        "status = \"available\""
        "requires = []"
        ""
        "[features.smart-build]"
        "description = \"Incremental build system with caching\""
        "source = \"p-jpl-website\""
        "status = \"available\""
        "requires = []"
        ""
        "[features.debugging-tools]"
        "description = \"Enhanced debugging capabilities\""
        "source = \"p-jpl-website\""
        "status = \"available\""
        "requires = []"
        ""
        "[features.ui-components]"
        "description = \"Reusable Leptos components\""
        "source = \"p-jpl-website\""
        "status = \"available\""
        "requires = []"
    ]

    $features_registry | str join "\n" | save --force $"($REGISTRY_PATH)/features.toml"
    print "  ✓ Features registry created"
}

# Run Phase 2 if requested
def run_phase_2 [] {
    print "🚀 Running Phase 2: Feature Extraction"

    mkdir features
    extract_analytics_feature
    extract_smart_build_feature
    create_features_registry

    print "✅ Phase 2 completed successfully!"
}

# Export functions for external use
export def phase_2 [] { run_phase_2 }
