#!/bin/bash
#
# Configuration setup
#

setup_configuration() {
    log_info "Setting up configuration..."
    
    # Generate secrets
    generate_secrets
    
    # Copy configuration templates
    copy_configuration_templates
    
    # Setup environment file
    setup_environment_file
    
    log_info "✓ Configuration setup complete"
}

generate_secrets() {
    log_info "Generating secrets..."
    
    # Generate JWT secret if not set
    if [[ -z "${CALYPSO_JWT_SECRET:-}" ]]; then
        CALYPSO_JWT_SECRET=$(generate_jwt_secret)
    fi
    
    # Store secrets
    echo "CALYPSO_JWT_SECRET=$CALYPSO_JWT_SECRET" > "$CONFIG_DIR/secrets.env"
    echo "CALYPSO_DB_PASSWORD=$CALYPSO_DB_PASSWORD" >> "$CONFIG_DIR/secrets.env"
    chmod 600 "$CONFIG_DIR/secrets.env"
    
    log_info "✓ Secrets generated and stored in $CONFIG_DIR/secrets.env"
}

copy_configuration_templates() {
    log_info "Copying configuration templates..."
    
    # Copy main config if it doesn't exist
    if [[ ! -f "$CONFIG_DIR/config.yaml" ]]; then
        if [[ -f "$PROJECT_ROOT/backend/config.yaml.example" ]]; then
            cp "$PROJECT_ROOT/backend/config.yaml.example" "$CONFIG_DIR/config.yaml"
            log_info "✓ Configuration file created: $CONFIG_DIR/config.yaml"
        else
            # Create minimal config
            create_minimal_config
        fi
    else
        log_info "Configuration file already exists, skipping..."
    fi
}

create_minimal_config() {
    cat > "$CONFIG_DIR/config.yaml" <<EOF
# AtlasOS - Calypso API Configuration
server:
  port: 8080
  host: "0.0.0.0"
  read_timeout: 15s
  write_timeout: 15s
  idle_timeout: 60s
  cache:
    enabled: true
    default_ttl: 5m
    max_age: 300

database:
  host: "localhost"
  port: 5432
  user: "calypso"
  password: ""  # Set via CALYPSO_DB_PASSWORD environment variable
  database: "calypso"
  ssl_mode: "disable"
  max_connections: 25
  max_idle_conns: 5
  conn_max_lifetime: 5m

auth:
  jwt_secret: ""  # Set via CALYPSO_JWT_SECRET environment variable
  token_lifetime: 24h
  argon2:
    memory: 65536
    iterations: 3
    parallelism: 4
    salt_length: 16
    key_length: 32

logging:
  level: "info"
  format: "json"
EOF
    log_info "✓ Minimal configuration file created"
}

setup_environment_file() {
    log_info "Setting up environment file..."
    
    # Create systemd environment file
    mkdir -p /etc/systemd/system/calypso-api.service.d/
    cat > /etc/systemd/system/calypso-api.service.d/env.conf <<EOF
[Service]
EnvironmentFile=$CONFIG_DIR/secrets.env
EOF
    
    log_info "✓ Environment file configured"
}

