#!/usr/bin/env bash
# ~/.local/bin/font-manager
# This script extracts font archives and rebuilds font cache
# Enhanced version with better integration and error handling

FONT_DIR="$HOME/.local/share/fonts"
ARCHIVE_DIR="$FONT_DIR/archives"
ACTIVE_DIR="$FONT_DIR/active"
BACKUP_DIR="$FONT_DIR/backups"
LOG_FILE="$HOME/.local/share/font-manager.log"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging function
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

# Error handling
error_exit() {
    echo -e "${RED}Error: $1${NC}" >&2
    log "ERROR: $1"
    exit 1
}

# Success message
success() {
    echo -e "${GREEN}$1${NC}"
    log "SUCCESS: $1"
}

# Warning message
warning() {
    echo -e "${YELLOW}Warning: $1${NC}"
    log "WARNING: $1"
}

# Info message
info() {
    echo -e "${BLUE}$1${NC}"
    log "INFO: $1"
}

# Initialize directories
init_directories() {
    mkdir -p "$ARCHIVE_DIR" "$ACTIVE_DIR" "$BACKUP_DIR"
    log "Initialized font directories"
}

# Function to extract a specific font archive
extract_font() {
    local archive="$1"
    if [ -z "$archive" ]; then
        error_exit "Archive name required"
    fi
    
    if [ ! -f "$ARCHIVE_DIR/$archive.tar.gz" ]; then
        error_exit "Font archive $archive.tar.gz not found"
    fi
    
    # Validate archive integrity
    if ! tar -tzf "$ARCHIVE_DIR/$archive.tar.gz" >/dev/null 2>&1; then
        error_exit "Archive $archive.tar.gz is corrupted"
    fi
    
    info "Extracting $archive fonts..."
    tar -xzf "$ARCHIVE_DIR/$archive.tar.gz" -C "$ACTIVE_DIR" || error_exit "Failed to extract $archive"
    
    # Rebuild font cache
    rebuild_cache
    success "$archive fonts are now active"
}

# Function to list available font archives
list_fonts() {
    if [ ! -d "$ARCHIVE_DIR" ] || [ -z "$(ls -A "$ARCHIVE_DIR" 2>/dev/null)" ]; then
        warning "No font archives found in $ARCHIVE_DIR"
        return 1
    fi
    
    info "Available font archives:"
    ls -1 "$ARCHIVE_DIR" | sed 's/\.tar\.gz$//' | while read -r font; do
        echo "  • $font"
    done
}

# Function to rebuild font cache
rebuild_cache() {
    info "Rebuilding font cache..."
    if fc-cache -f >/dev/null 2>&1; then
        success "Font cache rebuilt successfully"
    else
        error_exit "Failed to rebuild font cache"
    fi
}

# Function to extract all fonts
extract_all() {
    if [ ! -d "$ARCHIVE_DIR" ] || [ -z "$(ls -A "$ARCHIVE_DIR" 2>/dev/null)" ]; then
        warning "No font archives found to extract"
        return 1
    fi
    
    info "Extracting all font archives..."
    local count=0
    for archive in "$ARCHIVE_DIR"/*.tar.gz; do
        if [ -f "$archive" ]; then
            local basename=$(basename "$archive" .tar.gz)
            extract_font "$basename"
            ((count++))
        fi
    done
    success "Extracted $count font archives"
}

# Function to clean active fonts directory
clean_fonts() {
    if [ ! -d "$ACTIVE_DIR" ]; then
        warning "Active fonts directory does not exist"
        return 1
    fi
    
    # Create backup before cleaning
    local backup_name="backup_$(date +%Y%m%d_%H%M%S)"
    if [ -n "$(find "$ACTIVE_DIR" -type f -name "*.ttf" -o -name "*.otf" 2>/dev/null)" ]; then
        info "Creating backup: $backup_name"
        cp -r "$ACTIVE_DIR" "$BACKUP_DIR/$backup_name"
    fi
    
    info "Cleaning active fonts directory..."
    find "$ACTIVE_DIR" -type f \( -name "*.ttf" -o -name "*.otf" \) -delete
    rebuild_cache
    success "Active fonts directory cleaned"
}

# Function to restore from backup
restore_fonts() {
    local backup="$1"
    if [ -z "$backup" ]; then
        error_exit "Backup name required"
    fi
    
    if [ ! -d "$BACKUP_DIR/$backup" ]; then
        error_exit "Backup $backup not found"
    fi
    
    info "Restoring fonts from backup: $backup"
    cp -r "$BACKUP_DIR/$backup"/* "$ACTIVE_DIR/"
    rebuild_cache
    success "Fonts restored from backup: $backup"
}

# Function to list backups
list_backups() {
    if [ ! -d "$BACKUP_DIR" ] || [ -z "$(ls -A "$BACKUP_DIR" 2>/dev/null)" ]; then
        warning "No backups found"
        return 1
    fi
    
    info "Available backups:"
    ls -1 "$BACKUP_DIR" | while read -r backup; do
        echo "  • $backup"
    done
}

# Function to install font from URL
install_from_url() {
    local url="$1"
    local name="$2"
    
    if [ -z "$url" ]; then
        error_exit "URL required"
    fi
    
    if [ -z "$name" ]; then
        name=$(basename "$url" | sed 's/\.[^.]*$//')
    fi
    
    info "Downloading font from: $url"
    if wget -q "$url" -O "$ARCHIVE_DIR/$name.tar.gz"; then
        success "Downloaded $name"
        extract_font "$name"
    else
        error_exit "Failed to download font from $url"
    fi
}

# Main script logic
init_directories

case "$1" in
"extract")
    extract_font "$2"
    ;;
"list")
    list_fonts
    ;;
"rebuild")
    rebuild_cache
    ;;
"all")
    extract_all
    ;;
"clean")
    clean_fonts
    ;;
"backup")
    list_backups
    ;;
"restore")
    restore_fonts "$2"
    ;;
"install")
    install_from_url "$2" "$3"
    ;;
"status")
    info "Font Manager Status:"
    echo "  Archives: $ARCHIVE_DIR"
    echo "  Active: $ACTIVE_DIR"
    echo "  Backups: $BACKUP_DIR"
    echo "  Log: $LOG_FILE"
    echo ""
    list_fonts
    echo ""
    list_backups
    ;;
*)
    echo "Usage: font-manager [command] [options]"
    echo ""
    echo "Commands:"
    echo "  extract [name]     Extract specific font archive"
    echo "  list               List available font archives"
    echo "  rebuild            Rebuild font cache"
    echo "  all                Extract all font archives"
    echo "  clean              Remove all active fonts (with backup)"
    echo "  backup             List available backups"
    echo "  restore [name]     Restore fonts from backup"
    echo "  install [url] [name] Install font from URL"
    echo "  status             Show current status"
    echo ""
    echo "Examples:"
    echo "  font-manager extract jetbrains-mono"
    echo "  font-manager install https://github.com/JetBrains/JetBrainsMono/releases/download/v2.304/JetBrainsMono-2.304.zip"
    echo "  font-manager status"
    ;;
esac
