#!/usr/bin/env nu
# Sync filesystem with SurrealDB storage backend (bidirectional)
#
# Usage: nu kogral-sync.nu [--direction <to-storage|from-storage|bidirectional>] [--dry-run]

def main [
    --direction: string = "bidirectional"  # Sync direction
    --dry-run                              # Show what would be synced without making changes
    --kogral-dir: string = ".kogral"       # KOGRAL directory
] {
    print $"(ansi green_bold)KOGRAL Sync(ansi reset)"
    print $"Direction: ($direction)"
    print $"KOGRAL Directory: ($kogral_dir)"

    if $dry_run {
        print $"(ansi yellow)DRY RUN MODE - No changes will be made(ansi reset)"
    }

    # Check if .kogral directory exists
    if not ($kogral_dir | path exists) {
        print $"(ansi red)Error: KOGRAL directory not found: ($kogral_dir)(ansi reset)"
        exit 1
    }

    # Verify kogral CLI is available
    if (which kogral | is-empty) {
        print $"(ansi red)Error: 'kogral' CLI not found. Install with: cargo install --path crates/kogral-cli(ansi reset)"
        exit 1
    }

    # Count files to sync
    print $"\n(ansi cyan_bold)Scanning files...(ansi reset)"
    let notes_count = (glob $"($kogral_dir)/**/notes/**/*.md" | length)
    let decisions_count = (glob $"($kogral_dir)/**/decisions/**/*.md" | length)
    let guidelines_count = (glob $"($kogral_dir)/**/guidelines/**/*.md" | length)
    let patterns_count = (glob $"($kogral_dir)/**/patterns/**/*.md" | length)

    let total_files = $notes_count + $decisions_count + $guidelines_count + $patterns_count

    print $"  Notes:      ($notes_count)"
    print $"  Decisions:  ($decisions_count)"
    print $"  Guidelines: ($guidelines_count)"
    print $"  Patterns:   ($patterns_count)"
    print $"  Total:      ($total_files)"

    if $total_files == 0 {
        print $"\n(ansi yellow)No files to sync(ansi reset)"
        exit 0
    }

    # Perform sync based on direction
    print $"\n(ansi cyan_bold)Starting sync...(ansi reset)"

    match $direction {
        "to-storage" => {
            sync_to_storage $kogral_dir $dry_run
        },
        "from-storage" => {
            sync_from_storage $kogral_dir $dry_run
        },
        "bidirectional" => {
            print "Step 1: Syncing to storage..."
            sync_to_storage $kogral_dir $dry_run
            print "\nStep 2: Syncing from storage..."
            sync_from_storage $kogral_dir $dry_run
        },
        _ => {
            print $"(ansi red)Error: Invalid direction. Use: to-storage, from-storage, or bidirectional(ansi reset)"
            exit 1
        }
    }

    print $"\n(ansi green_bold)✓ Sync completed(ansi reset)"
}

def sync_to_storage [kogral_dir: string, dry_run: bool] {
    print "  → Uploading markdown files to storage backend..."

    if $dry_run {
        print $"    (ansi yellow)[DRY RUN](ansi reset) Would upload all markdown files"
        return
    }

    # Phase 1: Execute sync to storage
    kogral --project . sync
    print $"    (ansi green)✓ Upload completed(ansi reset)"
}

def sync_from_storage [kogral_dir: string, dry_run: bool] {
    print "  ← Downloading nodes from storage backend..."

    if $dry_run {
        print $"    (ansi yellow)[DRY RUN](ansi reset) Would download all nodes"
        return
    }

    # Phase 2: Execute sync from storage
    kogral --project . sync
    print $"    (ansi green)✓ Download completed(ansi reset)"
}
