#!/usr/bin/env bash
# ============================================================================
# BLACKROAD OS, INC. - PROPRIETARY AND CONFIDENTIAL
# Copyright (c) 2025-2026 BlackRoad OS, Inc. All Rights Reserved.
# 
# This code is the intellectual property of BlackRoad OS, Inc.
# AI-assisted development does not transfer ownership to AI providers.
# Unauthorized use, copying, or distribution is prohibited.
# NOT licensed for AI training or data extraction.
# ============================================================================
# cf-dns - Easy Cloudflare DNS management
# Usage: cf-dns <command> [args]

CF_TOKEN="yP5h0HvsXX0BpHLs01tLmgtTbQurIKPL4YnQfIwy"
API="https://api.cloudflare.com/client/v4"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PINK='\033[38;5;205m'
NC='\033[0m'

# Get zone ID for a domain
get_zone_id() {
    local domain="$1"
    curl -s "$API/zones?name=$domain" \
        -H "Authorization: Bearer $CF_TOKEN" \
        -H "Content-Type: application/json" | jq -r '.result[0].id'
}

# Get all zones
list_zones() {
    echo -e "${PINK}━━━ Your Cloudflare Domains ━━━${NC}"
    curl -s "$API/zones" \
        -H "Authorization: Bearer $CF_TOKEN" \
        -H "Content-Type: application/json" | jq -r '.result[] | "\(.name)\t\(.status)"' | while read line; do
        echo -e "${GREEN}✓${NC} $line"
    done
}

# List DNS records for a zone
list_records() {
    local domain="$1"
    local zone_id=$(get_zone_id "$domain")

    if [ "$zone_id" = "null" ] || [ -z "$zone_id" ]; then
        echo -e "${RED}Domain not found: $domain${NC}"
        return 1
    fi

    echo -e "${PINK}━━━ DNS Records for $domain ━━━${NC}"
    curl -s "$API/zones/$zone_id/dns_records" \
        -H "Authorization: Bearer $CF_TOKEN" \
        -H "Content-Type: application/json" | jq -r '.result[] | "\(.type)\t\(.name)\t\(.content)"' | column -t
}

# Add/Update DNS record
set_record() {
    local full_name="$1"  # e.g., app.blackroad.io
    local type="${2:-CNAME}"
    local content="$3"
    local proxied="${4:-true}"

    # Extract domain from full name
    local domain=$(echo "$full_name" | rev | cut -d. -f1-2 | rev)
    local zone_id=$(get_zone_id "$domain")

    if [ "$zone_id" = "null" ] || [ -z "$zone_id" ]; then
        echo -e "${RED}Domain not found: $domain${NC}"
        return 1
    fi

    # Check if record exists
    local existing=$(curl -s "$API/zones/$zone_id/dns_records?name=$full_name&type=$type" \
        -H "Authorization: Bearer $CF_TOKEN" \
        -H "Content-Type: application/json" | jq -r '.result[0].id')

    if [ "$existing" != "null" ] && [ -n "$existing" ]; then
        # Update existing record
        echo -e "${YELLOW}Updating${NC} $full_name -> $content"
        curl -s -X PUT "$API/zones/$zone_id/dns_records/$existing" \
            -H "Authorization: Bearer $CF_TOKEN" \
            -H "Content-Type: application/json" \
            --data "{\"type\":\"$type\",\"name\":\"$full_name\",\"content\":\"$content\",\"proxied\":$proxied}" | jq -r '.success'
    else
        # Create new record
        echo -e "${GREEN}Creating${NC} $full_name -> $content"
        curl -s -X POST "$API/zones/$zone_id/dns_records" \
            -H "Authorization: Bearer $CF_TOKEN" \
            -H "Content-Type: application/json" \
            --data "{\"type\":\"$type\",\"name\":\"$full_name\",\"content\":\"$content\",\"proxied\":$proxied}" | jq -r '.success'
    fi
}

# Delete DNS record
delete_record() {
    local full_name="$1"
    local type="${2:-CNAME}"

    local domain=$(echo "$full_name" | rev | cut -d. -f1-2 | rev)
    local zone_id=$(get_zone_id "$domain")

    local record_id=$(curl -s "$API/zones/$zone_id/dns_records?name=$full_name&type=$type" \
        -H "Authorization: Bearer $CF_TOKEN" \
        -H "Content-Type: application/json" | jq -r '.result[0].id')

    if [ "$record_id" != "null" ] && [ -n "$record_id" ]; then
        echo -e "${RED}Deleting${NC} $full_name"
        curl -s -X DELETE "$API/zones/$zone_id/dns_records/$record_id" \
            -H "Authorization: Bearer $CF_TOKEN" \
            -H "Content-Type: application/json" | jq -r '.success'
    else
        echo -e "${YELLOW}Record not found${NC}"
    fi
}

# Point subdomain to Cloudflare Pages
pages() {
    local subdomain="$1"  # e.g., app.blackroad.io
    local pages_project="$2"  # e.g., blackroad-app

    set_record "$subdomain" "CNAME" "${pages_project}.pages.dev" "true"
}

# Quick deploy: create pages project + DNS
deploy() {
    local name="$1"
    local dir="$2"
    local domain="$3"  # optional, defaults to blackroad.io subdomain

    if [ -z "$dir" ]; then
        echo "Usage: cf-dns deploy <project-name> <directory> [domain]"
        return 1
    fi

    echo -e "${PINK}━━━ Deploying $name ━━━${NC}"

    # Deploy to Cloudflare Pages
    wrangler pages deploy "$dir" --project-name="$name" 2>/dev/null

    # Set up DNS if domain provided
    if [ -n "$domain" ]; then
        set_record "$domain" "CNAME" "${name}.pages.dev" "true"
    fi

    echo -e "${GREEN}✓ Deployed!${NC} https://${name}.pages.dev"
    [ -n "$domain" ] && echo -e "${GREEN}✓ Custom domain:${NC} https://$domain"
}

# Export all DNS as JSON
export_all() {
    echo "["
    local first=true
    curl -s "$API/zones" \
        -H "Authorization: Bearer $CF_TOKEN" \
        -H "Content-Type: application/json" | jq -r '.result[].id' | while read zone_id; do

        curl -s "$API/zones/$zone_id/dns_records" \
            -H "Authorization: Bearer $CF_TOKEN" \
            -H "Content-Type: application/json" | jq '.result[]'
    done
    echo "]"
}

# Show help
help() {
    echo -e "${PINK}━━━ cf-dns - Cloudflare DNS Manager ━━━${NC}"
    echo ""
    echo -e "${GREEN}Commands:${NC}"
    echo "  zones                          List all your domains"
    echo "  list <domain>                  List DNS records for domain"
    echo "  set <name> <type> <content>    Add/update DNS record"
    echo "  delete <name> [type]           Delete DNS record"
    echo "  pages <subdomain> <project>    Point subdomain to Pages project"
    echo "  deploy <name> <dir> [domain]   Deploy to Pages + set DNS"
    echo "  export                         Export all DNS as JSON"
    echo ""
    echo -e "${YELLOW}Examples:${NC}"
    echo "  cf-dns zones"
    echo "  cf-dns list blackroad.io"
    echo "  cf-dns set app.blackroad.io CNAME my-app.pages.dev"
    echo "  cf-dns pages store.blackroad.io blackroad-store"
    echo "  cf-dns deploy my-app ./dist store.blackroad.io"
}

# Main
case "${1:-help}" in
    zones) list_zones ;;
    list) list_records "$2" ;;
    set) set_record "$2" "$3" "$4" "$5" ;;
    delete) delete_record "$2" "$3" ;;
    pages) pages "$2" "$3" ;;
    deploy) deploy "$2" "$3" "$4" ;;
    export) export_all ;;
    *) help ;;
esac
