#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case bundling);
use Pod::Usage;
use JSON::XS;
use File::Path qw(make_path);
use Cwd        qw(abs_path);
use FindBin;
use File::Find;
use Text::CSV_XS;
use Data::Dumper;
use IPC::Run qw(run);

my @SUPPORTED_BRANDS =
  qw(bluehost hostgator hostgator_br hostgator_co hostgator_mx hostgator_cl hostgator_la crazydomains vodien bigrock_in hostgator_in webhostbox digitalpacific panthur crucial web24 networksolutions);
my @SUPPORTED_TENANTS = qw(bhhosting bhpreprodhosting lahosting lapreprodhosting dsnhosting dsnpreprodhosting inhosting inpreprodhosting wnhosting wnpreprodhosting);

my %BRAND_ORG_MAP = (
    'bluehost'       => 'BLUEHOST',
    'hostgator'      => 'HOSTGATOR',
    'hostgator_br'   => 'LATAM',
    'hostgator_co'   => 'LATAM',
    'hostgator_mx'   => 'LATAM',
    'hostgator_cl'   => 'LATAM',
    'hostgator_la'   => 'LATAM',
    'crazydomains'   => 'DREAMSCAPE',
    'vodien',        => 'DREAMSCAPE',
    'bigrock_in'     => 'DIRECTI',
    'hostgator_in'   => 'DIRECTI',
    'webhostbox'     => 'DIRECTI',
    'digitalpacific' => 'DIGITALPACIFIC',
    'panthur'        => 'DIGITALPACIFIC',
    'crucial'        => 'DIGITALPACIFIC',
    'web24'          => 'DIGITALPACIFIC',
    'networksolutions' => 'ASO'
);
my %DINO_JOBS_URL = (
    dev => {
        _default          => 'https://dino.beta.bh1.hosting.newfold.com/jobs',
        dsnpreprodhosting => 'https://dino.beta.sydney.hosting.newfold.com/jobs',
        inpreprodhosting  => 'https://dino.beta.ns-hal1.hosting.newfold.com/jobs',
        wnpreprodhosting  => 'https://dino.beta.ns-hal1.hosting.newfold.com/jobs',
    },
    prod => {
        _default   => 'https://dino.bh.hosting.newfold.com/jobs',
        dsnhosting => 'https://dino.sydney.hosting.newfold.com/jobs',
        inhosting  => 'https://dino.ns-hal.hosting.newfold.com/jobs',
        wnhosting  => 'https://dino.ns-hal.hosting.newfold.com/jobs',
    },
);
my @SUPPORTED_REGIONS = qw(
  us-ashburn-1
  us-phoenix-1
  eu-frankfurt-1
  sa-saopaulo-1
  eu-madrid-1
  ap-singapore-1
  ap-singapore-2
  sa-valparaiso-1
  sa-bogota-1
  mx-monterrey-1
  ap-mumbai-1
  ap-sydney-1
  uk-london-1
  eu-paris-1
  sa-vinhedo-1
  ca-toronto-1
);
my @CUSTOMER_PHASES        = qw(net-new migration);
my @SUPPORTED_PANELS       = qw(cpanel destiny none alma);
my @SUPPORTED_FLAVORS      = qw(cpanel destiny none);
my @SUPPORTED_SHAPES       = qw(e5 e6);
my @SUPPORTED_ATTACH_TYPES = qw(paravirtualized iscsi);
my @TASKS = qw(instance-create instance-status instance-terminate job-restart image-create spawn-create-image instance-schedule-terminate instance-upgrade volume-resize volume-add public-ip-reattach attach-shared-ip);
my @ENVIRONMENTS = qw(dev prod);
my @BOOLEAN_ARGS = qw(true false);

our %opts = (
    debug                   => 0,
    task                    => '',
    job_id                  => '',
    env                     => '',
    brand                   => '',
    region                  => '',
    tenant                  => '',
    verbose                 => 0,
    hostname                => '',
    customer_phase          => '',
    purpose                 => '',
    panel                   => 'cpanel',
    flavor                  => 'cpanel',
    set_active              => undef,
    force_active            => undef,
    verify_image            => 'false',
    update_root_image       => undef,
    ips_secondary           => '',
    ip                      => '',
    ips                     => '',
    subnet_cidr             => '',
    metadata                => '',
    auto_delete             => '',
    dry_run                 => 0,
    subnet_id               => '',
    ip_primary              => '',
    register_hal            => '',
    verify_hosting_site     => '',
    instance_id             => '',
    complete                => 0,
    current                 => '',
    prev                    => '',
    shape                   => '',
    resources_config        => '',
    volumes_config          => '',
    volumes                 => '',
    instance_config         => '',
    monitor                 => 0,
    vcn_name                => '',
    expedite                => 0,
    name_equals             => '',
    capacity_reservation_id => '',
    capacity_reservation_auto => '',
    availability_domain     => '',
    batch                   => '',
    batch_name              => '',
    batch_job_type          => 'migration',
    concurrency             => 5,
    ip_count                => undef,
    ip_type                 => '',
    memory                  => '',
    cpu                     => '',
    reboot_hard             => undef,
    timeout_per_step        => 1200,
    owner                   => '',
    ip_max_per_vnic         => undef,
    ip_mgmt_count           => undef,
    migration_reset         => undef,
    volume_id               => '',
    new_size_gbs            => '',
    backup                  => 'n',
    size_gbs                => '',
    attach_type             => 'paravirtualized',
    display_name            => '',
    mount                   => '',
    batch_report            => 0,
    summary                 => 0,
    batch_create_only       => 0,
    subtype                 => '',
    ssh_keys                => '',
);

our $DINO_URL = '';
our $DINO_JWT = '';
my $base_file = $FindBin::Script;

my $_batch_child_job_cache = {};

sub _help;
sub _load_dino_jwt;
sub _resolve_dino_url;
sub _configure_dino;
sub _log_message;
sub _decode_dino_response;
sub _instance_create;
sub _instance_status;
sub _instance_terminate;
sub _public_ip_reattach;
sub _attach_shared_ip;
sub _image_create;
sub _spawn_create_image;
sub _handle_task;
sub _generate_completions;
sub _instance_schedule_terminate;
sub _build_instance_upgrade_args;
sub _build_volume_add_args;
sub _batch_instance_upgrade;
sub _batch_volume_add;
sub _instance_upgrade;
sub _volume_resize;
sub _volume_add;
sub _validate_attach_type;
sub _build_instance_args;
sub _batch_instance_create;
sub _dino_http_json;
sub _run_dino_rest_post;
sub _dino_get_job;
sub _wait_for_job;
sub _print_batch_child_status_lines;
sub _print_batch_summary;
sub _format_duration_seconds;

_setup_dino_dirs();

my @original_args = @ARGV;

GetOptions(
    'd|debug'                   => \$opts{debug},
    't|task=s'                  => \$opts{task},
    'j|job-id=s'                => \$opts{job_id},
    'e|env=s'                   => \$opts{env},
    'b|brand=s'                 => \$opts{brand},
    'r|region=s'                => \$opts{region},
    'o|tenant=s'                => \$opts{tenant},
    'v|verbose'                 => \$opts{verbose},
    'h|hostname=s'              => \$opts{hostname},
    'p|customer-phase=s'        => \$opts{customer_phase},
    'l|panel=s'                 => \$opts{panel},
    'flavor=s'                  => \$opts{flavor},
    'set-active=s'              => \$opts{set_active},
    'force-active=s'            => \$opts{force_active},
    'verify-image=s'            => \$opts{verify_image},
    'update-root-image=s'       => \$opts{update_root_image},
    'u|purpose=s'               => \$opts{purpose},
    'i|ips-secondary=s'         => \$opts{ips_secondary},
    'm|metadata=s'              => \$opts{metadata},
    'ip=s'                      => \$opts{ip},
    'ips=s'                     => \$opts{ips},
    'subnet-cidr=s'             => \$opts{subnet_cidr},
    'a|auto-delete=s'           => \$opts{auto_delete},
    'x|dry-run'                 => \$opts{dry_run},
    's|subnet-id=s'             => \$opts{subnet_id},
    'ip-primary=s'              => \$opts{ip_primary},
    'g|register-hal=s'          => \$opts{register_hal},
    'y|verify-hosting-site=s'   => \$opts{verify_hosting_site},
    'k|instance-id=s'           => \$opts{instance_id},
    'complete'                  => \$opts{complete},
    'current=s'                 => \$opts{current},
    'prev=s'                    => \$opts{prev},
    'shape=s'                   => \$opts{shape},
    'resources-config=s'        => \$opts{resources_config},
    'volumes-config=s'          => \$opts{volumes_config},
    'volumes=s'                 => \$opts{volumes},
    'instance-config=s'         => \$opts{instance_config},
    'monitor'                   => \$opts{monitor},
    'vcn-name=s'                => \$opts{vcn_name},
    'expedite'                  => \$opts{expedite},
    'name-equals=s'             => \$opts{name_equals},
    'capacity-reservation-id=s'  => \$opts{capacity_reservation_id},
    'capacity-reservation-auto=s' => \$opts{capacity_reservation_auto},
    'availability-domain=s'      => \$opts{availability_domain},
    'batch=s'                   => \$opts{batch},
    'batch-name=s'              => \$opts{batch_name},
    'batch-job-type=s'          => \$opts{batch_job_type},
    'concurrency=i'             => \$opts{concurrency},
    'ip-count=i'                => \$opts{ip_count},
    'ip-type=s'                 => \$opts{ip_type},
    'memory=i'                  => \$opts{memory},
    'cpu=i'                     => \$opts{cpu},
    'reboot-hard!'              => \$opts{reboot_hard},
    'timeout-per-step=i'        => \$opts{timeout_per_step},
    'owner=s'                   => \$opts{owner},
    'ip-max-per-vnic=i'         => \$opts{ip_max_per_vnic},
    'ip-mgmt-count=i'           => \$opts{ip_mgmt_count},
    'migration-reset=s'         => \$opts{migration_reset},
    'volume-id=s'               => \$opts{volume_id},
    'new-size-gbs=s'            => \$opts{new_size_gbs},
    'backup=s'                  => \$opts{backup},
    'size-gbs=s'                => \$opts{size_gbs},
    'attach-type=s'             => \$opts{attach_type},
    'display-name=s'            => \$opts{display_name},
    'mount=s'                   => \$opts{mount},
    'batch-report'              => \$opts{batch_report},
    'summary'                   => \$opts{summary},
    'batch-create-only'         => \$opts{batch_create_only},
    'subtype=s'                 => \$opts{subtype},
    'ssh-keys=s'                => \$opts{ssh_keys},
) or _help();

if ( $opts{batch_report} && ( $opts{task} // '' ) ne 'instance-status' ) {
    warn "--batch-report is only valid for --task instance-status.\n";
    exit 1;
}

if ( $opts{batch_report} && $opts{dry_run} ) {
    warn "--batch-report has no effect with --dry-run (child job IDs are not available).\n";
}

if ( $opts{summary} && ( $opts{task} // '' ) ne 'instance-status' ) {
    warn "--summary is only valid for --task instance-status.\n";
    exit 1;
}

if ( $opts{summary} && $opts{batch_report} ) {
    warn "--batch-report is ignored when --summary is set (no child job fetches).\n";
}

if ( $opts{monitor} && $opts{dry_run} ) {
    warn "--monitor and --dry-run are mutually exclusive.\n";
    exit 1;
}

if ( defined $opts{ip_max_per_vnic} && defined $opts{ip_count} ) {
    warn "--ip-max-per-vnic and --ip-count are mutually exclusive.\n";
    exit 1;
}

if ( defined $opts{ip_max_per_vnic} ) {
    unless ( $opts{ip_primary} && $opts{ips_secondary} ) {
        warn "--ip-primary and --ips-secondary are mandatory when --ip-max-per-vnic is used.\n";
        exit 1;
    }
}

if ( $opts{complete} ) {
    _generate_completions( $opts{current}, $opts{prev} );
    exit 0;
}

_handle_task() unless $ENV{OCI_SERVER_CREATE_TEST_LOAD_ONLY};

sub _setup_dino_dirs {
    my $dino_home = "$ENV{HOME}/.dino";
    my $log_dir   = "$dino_home/logs";
    my $token_dir = "$dino_home/tokens";

    unless ( -d $log_dir && -d $token_dir ) {
        make_path( $log_dir, $token_dir, { mode => 0700 } ) or die "Failed to create ~/.dino/{logs,tokens}: $!\n";
    }
    else {
        chmod 0700, $log_dir, $token_dir or warn "Failed to chmod ~/.dino/{logs,tokens}: $!\n";
        File::Find::find(
            sub {
                if ( -f $_ ) {
                    chmod 0600, $_ or warn "Failed to chmod $_: $!\n";
                }
            },
            $log_dir,
            $token_dir
        );
    }
}

sub _decode_dino_response {
    my ( $json, $body, $context ) = @_;
    my $data = eval { $json->decode($body) };
    return $data unless $@;
    my $err = $@;
    chomp $err;
    warn "DINO response is not valid JSON ($context): $err\n";
    warn "Raw response: $body\n" if length $body;
    _log_message("invalid_json ($context): $body");
    return;
}

# DINO HTTP helper: GET or POST JSON, decode body. on_fail fatal => exit 1; soft => return undef.
sub _dino_http_json {
    my (%arg)   = @_;
    my $method  = $arg{method} // 'GET';
    my $url     = $arg{url}  or die "_dino_http_json: url required\n";
    my $json    = $arg{json} or die "_dino_http_json: json decoder required\n";
    my $context = $arg{context} // 'dino_http';
    my $on_fail = $arg{on_fail} // 'fatal';
    my $retries = $arg{max_retries} // 3;
    my $delay   = $arg{retry_delay} // 5;

    my $attempt = 0;
    while ( $attempt <= $retries ) {
        my ( $output, $stderr ) = ( '', '' );
        my $http_code = '';

        my @curl_args = ( 'curl', '-s', '-w', '%{http_code}', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT" );

        if ( $method eq 'POST' ) {
            my $body = $arg{body};
            defined $body or die "_dino_http_json: POST requires body\n";
            push @curl_args, ( '-X', 'POST', '--data-binary', '@-' );
            run [ @curl_args, $url ], '<', \$body, '>', \$output, '2>', \$stderr;
        }
        else {
            run [ @curl_args, $url ], '>', \$output, '2>', \$stderr;
        }

        $http_code = substr( $output, -3 );
        $output    = substr( $output, 0, -3 );
        my $exit_code = $? >> 8;

        my $err_msg;
        if ( $exit_code == 0 && $http_code =~ /^2\d\d/ ) {
            my $decoded = _decode_dino_response( $json, $output, $context );
            if ( defined $decoded ) {
                _log_message("command_output: $output") if $arg{log_success_output};
                return $decoded;
            }
            $err_msg = "Invalid JSON response ($context, attempt " . ( $attempt + 1 ) . "/" . ( $retries + 1 ) . ")";
        }
        else {
            $err_msg = "Request failed ($context, attempt " . ( $attempt + 1 ) . "/" . ( $retries + 1 ) . "): Exit $exit_code, HTTP $http_code";
            $err_msg .= ": $output" if $output;
        }

        warn "$err_msg\n";
        _log_message("command_error: $err_msg");

        if ( $attempt < $retries ) {
            $attempt++;
            sleep $delay;
            next;
        }

        if ( $on_fail eq 'soft' ) {
            if ( my $cb = $arg{on_soft_fail_warn} ) {
                $cb->( $exit_code, $output );
            }
            return;
        }
        exit 1;
    }
}

sub _dino_get_job {
    my ( $json, $job_id ) = @_;
    return unless defined $job_id && $job_id ne '';

    my $job_url = "$DINO_URL/$job_id";
    return _dino_http_json(
        method            => 'GET',
        url               => $job_url,
        json              => $json,
        context           => "instance-status child $job_id",
        on_fail           => 'soft',
        on_soft_fail_warn => sub {
            my ( $code, $out ) = @_;
            warn "GET job $job_id failed (exit $code): $out\n";
        },
    );
}

# Poll GET /jobs/{id} until status matches (default completed). Dies on errored/cancelled/timeout.
sub _wait_for_job {
    my ( $json, $job_id, %arg ) = @_;
    my $want_status = $arg{status}   // 'completed';
    my $timeout     = $arg{timeout}  // 600;
    my $interval    = $arg{interval} // 5;
    my $context     = $arg{context}  // "job $job_id";
    my $deadline    = time + $timeout;

    while (1) {
        my $job = _dino_get_job( $json, $job_id );
        if ($job) {
            my $status = $job->{status} // '';
            if ( $status eq $want_status ) {
                return $job;
            }
            if ( $status =~ /^(?:errored|cancelled)$/ ) {
                die "$context ended with status='$status' (id=$job_id)\n";
            }
            print "Waiting for $context: status=$status (id=$job_id)\n";
        }
        else {
            print "Waiting for $context: unable to fetch job (id=$job_id)\n";
        }

        if ( time >= $deadline ) {
            my $last = $job ? ( $job->{status} // 'unknown' ) : 'unreachable';
            die "Timed out after ${timeout}s waiting for $context to reach status='$want_status' (last=$last, id=$job_id)\n";
        }
        sleep $interval;
    }
}

sub _batch_report_parent_action {
    my ($action) = @_;
    return 0 unless defined $action;
    return 1 if $action eq 'job.batch_migration:run';
    return 1 if $action eq 'job.batch.create:run';
    return 1 if $action eq 'job.batch.run:run';
    return 0;
}

sub _format_duration_seconds {
    my ($seconds) = @_;
    return '0s' unless defined $seconds && $seconds > 0;
    $seconds = int($seconds);
    if ( $seconds < 60 ) {
        return "${seconds}s";
    }
    my $minutes = int( $seconds / 60 );
    my $secs    = $seconds % 60;
    if ( $minutes < 60 ) {
        return $secs ? "${minutes}m ${secs}s" : "${minutes}m";
    }
    my $hours = int( $minutes / 60 );
    $minutes = $minutes % 60;
    return $minutes ? "${hours}h ${minutes}m" : "${hours}h";
}

sub _print_batch_summary {
    my ($parent_job_data) = @_;
    return unless $opts{summary};
    return unless _batch_report_parent_action( $parent_job_data->{action} // '' );

    my $job_id  = $parent_job_data->{id}      // $opts{job_id} // 'N/A';
    my $status  = $parent_job_data->{status}  // 'N/A';
    my $stage   = $parent_job_data->{stage}   // $parent_job_data->{stage_num} // 'N/A';
    my $elapsed = $parent_job_data->{elapsed};
    my $created = $parent_job_data->{created} // '';

    print STDERR "Batch $job_id: status=$status stage=$stage";
    print STDERR " elapsed=${elapsed}s" if defined $elapsed;
    print STDERR " created=$created"     if $created ne '';
    print STDERR "\n";

    my $bs = $parent_job_data->{data}{batch}{status};
    unless ( $bs && ref $bs eq 'HASH' ) {
        print STDERR "  (no data.batch.status in API response)\n";
        return;
    }

    my %counts = map { $_ => int( $bs->{$_} // 0 ) } qw(errored completed cancelled running queued pending);
    my $total  = 0;
    $total += $_ for values %counts;

    my $completed = $counts{completed};
    my $terminal  = $counts{completed} + $counts{errored} + $counts{cancelled};
    my $remaining = $counts{pending} + $counts{queued} + $counts{running};
    my $pct       = $total > 0 ? sprintf( '%.1f', 100 * $terminal / $total ) : '0.0';

    print STDERR
      "  counts: errored=$counts{errored} completed=$completed cancelled=$counts{cancelled} running=$counts{running} queued=$counts{queued} pending=$counts{pending} (total=$total, ${pct}% done)\n";

    if ( defined $elapsed && $elapsed > 0 && $completed > 0 ) {
        my $rate_per_min = $completed / ( $elapsed / 60 );
        print STDERR sprintf( "  rate: %.2f jobs/min", $rate_per_min );
        if ( $remaining > 0 ) {
            my $eta_sec = int( $remaining * $elapsed / $completed );
            print STDERR "  ETA: ~" . _format_duration_seconds($eta_sec);
        }
        else {
            print STDERR "  ETA: done";
        }
        print STDERR "\n";
    }
    else {
        print STDERR "  rate: n/a  ETA: n/a\n";
    }
}

sub _resolve_batch_child_job_ids {
    my ( $parent_job_data, $json ) = @_;

    my $jobs = $parent_job_data->{data}{batch}{jobs};
    if ( $jobs && ref $jobs eq 'ARRAY' && @$jobs ) {
        return @$jobs;
    }

    my $batch_name = $parent_job_data->{args}{name};
    return unless defined $batch_name && $batch_name ne '';

    my $list_url = $DINO_URL . '?since=30d';
    my $all      = _dino_http_json(
        method  => 'GET',
        url     => $list_url,
        json    => $json,
        context => 'batch-child-list',
        on_fail => 'soft',
    );
    return unless $all && ref $all eq 'ARRAY';

    my @matched = grep {
        defined $_->{id}
          && ( ( $_->{data}{batch}{name} // '' ) eq $batch_name )
    } @$all;

    @matched = sort {
        ( $a->{data}{batch}{index} // 1_000_000 ) <=> ( $b->{data}{batch}{index} // 1_000_000 )
    } @matched;

    return map { $_->{id} } @matched;
}

sub _batch_child_status_is_terminal {
    my ($status) = @_;
    return 0 unless defined $status && $status ne '';
    return $status =~ /^(?:completed|errored|cancelled)$/;
}

sub _batch_child_label {
    my ($child) = @_;
    return '' unless $child && ref $child eq 'HASH';

    my $hostname = '';
    if ( ref( $child->{data} ) eq 'HASH' ) {
        $hostname = $child->{data}{hostname} // '';
    }
    if ( $hostname eq '' && ref( $child->{args} ) eq 'HASH' ) {
        $hostname = $child->{args}{hostname} // '';
        $hostname = $child->{args}{instance_id} // '' if $hostname eq '';
    }
    $hostname = "$hostname" if ref $hostname;
    return $hostname;
}

sub _print_batch_child_status_lines {
    my ($parent_job_data) = @_;
    return unless $opts{batch_report};
    return unless _batch_report_parent_action( $parent_job_data->{action} // '' );

    my $json = JSON::XS->new->utf8;
    my @child_ids = _resolve_batch_child_job_ids( $parent_job_data, $json );
    return unless @child_ids;

    my $csv_out = Text::CSV_XS->new( { binary => 1 } )
      or die "Failed to construct Text::CSV_XS for batch-report output: " . Text::CSV_XS->error_diag . "\n";

    for my $cid (@child_ids) {
        next unless defined $cid && $cid ne '';
        $cid = "$cid" if ref $cid;

        my $child;
        if ( exists $_batch_child_job_cache->{$cid} ) {
            $child = $_batch_child_job_cache->{$cid};
        }
        else {
            $child = _dino_get_job( $json, $cid );
            if ( $child && _batch_child_status_is_terminal( $child->{status} // '' ) ) {
                $_batch_child_job_cache->{$cid} = $child;
            }
        }
        unless ($child) {
            warn "Could not fetch child job $cid\n";
            if ( $csv_out->combine( $cid, '', '', '', 'none' ) ) {
                print $csv_out->string, "\n";
            }
            else {
                die "batch-report CSV combine failed: " . $csv_out->error_diag . "\n";
            }
            next;
        }

        my $hostname = _batch_child_label($child);
        my $stage    = $child->{stage}  // '';
        my $status   = $child->{status} // '';
        my $error    = $child->{error}  // '';
        $error  = "$error"  if ref $error;
        $stage  = "$stage"  if ref $stage;
        $status = "$status" if ref $status;
        $error  = 'none'    if $error eq '';

        if ( $csv_out->combine( $cid, $hostname, $stage, $status, $error ) ) {
            print $csv_out->string, "\n";
        }
        else {
            die "batch-report CSV combine failed: " . $csv_out->error_diag . "\n";
        }
    }
}

sub _log_message {
    my $message   = join ' ', @_;
    my $timestamp = `date +"%Y-%m-%d %H:%M:%S"`;
    chomp $timestamp;
    my $log_file = "$ENV{HOME}/.dino/logs/$base_file.log";
    open my $fh, '>>', $log_file or warn "Could not open log file $log_file: $!\n";
    print $fh "[$timestamp] $message\n" if $fh;
    close $fh                           if $fh;
}

sub _run_dino_curl {
    my ( $payload, $action ) = @_;
    my $json         = JSON::XS->new->utf8;
    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
        return;
    }

    return _dino_http_json(
        method             => 'POST',
        url                => $DINO_URL,
        body               => $json_payload,
        json               => $json,
        context            => $action,
        on_fail            => 'fatal',
        log_success_output => 1,
    );
}

sub _run_dino_rest_post {
    my ( $url, $body, $context ) = @_;
    my $json         = JSON::XS->new->utf8;
    my $json_payload = $json->encode($body);

    if ( $opts{dry_run} ) {
        print sprintf(
            q{curl -s -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer %s' --data '%s' '%s'\n},
            $DINO_JWT, $json_payload, $url
        );
        return;
    }

    return _dino_http_json(
        method             => 'POST',
        url                => $url,
        body               => $json_payload,
        json               => $json,
        context            => $context,
        on_fail            => 'fatal',
        log_success_output => 1,
    );
}

sub _help {
    pod2usage(
        {
            -exitval => 1,
            -verbose => 2,
            -message =>
"Usage: $base_file -e <dev|prod> -b <brand> -r <region> -t <instance-create|instance-status|instance-terminate|job-restart|image-create|spawn-create-image|instance-schedule-terminate|instance-upgrade|volume-resize|volume-add|public-ip-reattach|attach-shared-ip> -j (required if task instance-status or job-restart) -h (optional hostname) -p (optional customer_phase) -u (optional purpose)\n",
        }
    );
}

sub _load_dino_jwt {
    my ($env) = @_;
    my $token_file = "$ENV{HOME}/.dino/tokens/${env}_jwt";
    unless ( -f $token_file ) {
        die "Missing token $token_file\n";
    }
    open my $fh, '<', $token_file or die "Missing token $token_file: $!\n";
    my $line = <$fh>;
    close $fh;
    if ( $line =~ /_DINO_JWT=(.*)/ ) {
        my $jwt = $1;
        chomp $jwt;
        return $jwt;
    }
    die "Invalid token file format in $token_file\n";
}

sub _resolve_dino_url {
    my ( $env, $tenant ) = @_;
    unless ( $env && ( $env eq 'dev' || $env eq 'prod' ) ) {
        die "Invalid env \"$env\". Valid options are: (dev|prod)\n";
    }
    my $urls = $DINO_JOBS_URL{$env};
    if ( $tenant && exists $urls->{$tenant} ) {
        return $urls->{$tenant};
    }
    return $urls->{_default};
}

sub _configure_dino {
    my ( $env, $tenant ) = @_;
    $DINO_JWT = _load_dino_jwt($env);
    $DINO_URL = _resolve_dino_url( $env, $tenant );
}

sub _handle_task {
    if ( $opts{debug} ) {
        warn "Debug mode enabled.\n";
    }

    if ( $opts{task} !~
        /^(instance-create|instance-status|instance-terminate|job-restart|image-create|spawn-create-image|instance-schedule-terminate|instance-upgrade|volume-resize|volume-add|public-ip-reattach|attach-shared-ip)$/ )
    {
        warn
"Invalid task \"$opts{task}\". Valid options are: (instance-create|instance-status|instance-terminate|job-restart|image-create|spawn-create-image|instance-upgrade|volume-resize|volume-add|public-ip-reattach|attach-shared-ip)\n";
        _help();
    }

    if ( $opts{env} && ( $opts{env} eq 'dev' || $opts{env} eq 'prod' ) ) {
        _configure_dino( $opts{env}, '' );
        $opts{purpose} = 'userbox' if $opts{env} eq 'prod' && !$opts{purpose};
    }
    else {
        warn "Invalid or missing env \"$opts{env}\". Valid options are: (dev|prod)\n";
        _help();
    }

    if ( $opts{brand} ) {
        my $match = 0;
        for my $b (@SUPPORTED_BRANDS) {
            if ( $opts{brand} eq $b ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid brand \"$opts{brand}\". Supported brands: @SUPPORTED_BRANDS\n";
            exit 1;
        }
    }

    if ( $opts{task} eq 'spawn-create-image' && defined $opts{set_active} ) {
        warn "--set-active is not a valid argument for spawn-create-image. Use --force-active instead.\n";
        _help();
    }
    if ( $opts{task} eq 'image-create' && defined $opts{force_active} ) {
        warn "--force-active is not a valid argument for image-create. Use --set-active instead.\n";
        _help();
    }

    if ( $opts{region} ) {
        my $match = 0;
        for my $r (@SUPPORTED_REGIONS) {
            if ( $opts{region} eq $r ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid region \"$opts{region}\". Supported regions: @SUPPORTED_REGIONS\n";
            exit 1;
        }
    }

    if ( $opts{tenant} ) {
        my $match = 0;
        for my $t (@SUPPORTED_TENANTS) {
            if ( $opts{tenant} eq $t ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid tenant \"$opts{tenant}\". Supported tenants: @SUPPORTED_TENANTS\n";
            exit 1;
        }

        _configure_dino( $opts{env}, $opts{tenant} );

        if ( $opts{task} eq 'image-create' && $opts{region} ) {
            $opts{region} = $opts{tenant} . '/' . $opts{region};
        }
    }

    if ( $opts{customer_phase} && $opts{customer_phase} !~ /^(net-new|migration)$/ ) {
        warn "Invalid customer_phase \"$opts{customer_phase}\". Valid options are: (net-new|migration)\n";
        _help();
    }

    if ( $opts{panel} ) {
        my $match = 0;
        for my $p (@SUPPORTED_PANELS) {
            if ( $opts{panel} eq $p ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid panel \"$opts{panel}\". Supported panels: @SUPPORTED_PANELS\n";
            exit 1;
        }
    }

    if ( $opts{flavor} ) {
        my $match = 0;
        for my $f (@SUPPORTED_FLAVORS) {
            if ( $opts{flavor} eq $f ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid flavor \"$opts{flavor}\". Supported flavors: @SUPPORTED_FLAVORS\n";
            exit 1;
        }
    }

    if ( $opts{shape} ) {
        my $match = 0;
        for my $s (@SUPPORTED_SHAPES) {
            if ( $opts{shape} eq $s ) {
                $match = 1;
                last;
            }
        }
        unless ($match) {
            warn "Invalid shape \"$opts{shape}\". Supported shapes: @SUPPORTED_SHAPES\n";
            exit 1;
        }
    }

    if ( $opts{set_active} && $opts{set_active} !~ /^(true|false)$/ ) {
        warn "Invalid value for --set-active: \"$opts{set_active}\". Valid options are: (true|false)\n";
        _help();
    }

    if ( $opts{force_active} && $opts{force_active} !~ /^(true|false)$/ ) {
        warn "Invalid value for --force-active: \"$opts{force_active}\". Valid options are: (true|false)\n";
        _help();
    }

    if ( $opts{verify_image} && $opts{verify_image} !~ /^(true|false)$/ ) {
        warn "Invalid value for --verify-image: \"$opts{verify_image}\". Valid options are: (true|false)\n";
        _help();
    }

    if ( $opts{register_hal} && $opts{register_hal} !~ /^(true|false)$/ ) {
        warn "Invalid value for -g/--register-hal: \"$opts{register_hal}\". Valid options are: (true|false)\n";
        _help();
    }
    if ( $opts{verify_hosting_site} && $opts{verify_hosting_site} !~ /^(true|false)$/ ) {
        warn "Invalid value for -y/--verify-hosting-site: \"$opts{verify_hosting_site}\". Valid options are: (true|false)\n";
        _help();
    }

    if ( $opts{update_root_image} && $opts{update_root_image} !~ /^(true|false)$/ ) {
        warn "Invalid value for --update-root-image: \"$opts{update_root_image}\". Valid options are: (true|false)\n";
        _help();
    }

    if ( $opts{capacity_reservation_auto} && $opts{capacity_reservation_auto} !~ /^(true|false)$/ ) {
        warn "Invalid value for --capacity-reservation-auto: \"$opts{capacity_reservation_auto}\". Valid options are: (true|false)\n";
        _help();
    }

    if ( $opts{backup} && $opts{backup} !~ /^(y|n|yes|no|true|false)$/i ) {
        warn "Invalid value for --backup: \"$opts{backup}\". Valid options are: y, n, yes, no, true, false.\n";
        _help();
    }

    if ( $opts{subnet_id} && $opts{vcn_name} ) {
        warn "Cannot use both --subnet-id and --vcn-name at the same time.\n";
        _help();
    }

    if ( $opts{availability_domain} ) {
        if ( $opts{task} ne 'instance-create' ) {
            warn "--availability-domain is only supported for instance-create task.\n";
            _help();
        }
        if ( $opts{availability_domain} !~ /^\d$/ ) {
            warn "Invalid value for --availability-domain: \"$opts{availability_domain}\". It must be a single digit.\n";
            _help();
        }
    }

    if ( $opts{ssh_keys} && $opts{task} ne 'instance-create' ) {
        warn "--ssh-keys is only supported for instance-create task.\n";
        _help();
    }

    unless ($DINO_JWT) {
        warn "_DINO_JWT doesn't appear to be set, did you forget to export _DINO_JWT=<token> ?\n";
        exit 1;
    }

    _log_message( "command: $base_file " . join( ' ', @original_args ) );

    if ( $opts{task} eq 'instance-create' ) {
        if ( $opts{batch} ) {
            _batch_instance_create();
        }
        else {
            if ( $opts{purpose} && $opts{purpose} eq 'migration' && !$opts{hostname} ) {
                warn "Hostname is required for instance-create task when purpose is migration.\n";
                _help();
            }
            unless ( $opts{brand} && $opts{region} ) {
                warn "Brand and region are required for instance-create task.\n";
                _help();
            }
            _instance_create();
        }
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'image-create' ) {
        unless ( $opts{region} && $opts{flavor} ) {
            warn "Region and flavor are required for image-create task.\n";
            _help();
        }
        _image_create();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'spawn-create-image' ) {
        unless ( $opts{flavor} ) {
            warn "Flavor is required for spawn-create-image task.\n";
            _help();
        }
        _spawn_create_image();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'instance-terminate' ) {
        unless ( $opts{instance_id} ) {
            warn "Instance ID is required for instance-terminate task.\n";
            _help();
        }
        _instance_terminate();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'public-ip-reattach' ) {
        unless ( $opts{instance_id} ) {
            warn "Instance ID is required for public-ip-reattach task.\n";
            _help();
        }
        _public_ip_reattach();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'attach-shared-ip' ) {
        unless ( $opts{instance_id} ) {
            warn "Instance ID is required for attach-shared-ip task.\n";
            _help();
        }
        _attach_shared_ip();
    }
    elsif ( $opts{task} eq 'instance-status' ) {
        unless ( $opts{job_id} ) {
            warn "Job ID is required for instance-status task.\n";
            _help();
        }
        _instance_status();
    }
    elsif ( $opts{task} eq 'job-restart' ) {
        unless ( $opts{job_id} ) {
            warn "Job ID is required for job-restart task.\n";
            _help();
        }
        _job_restart();
    }
    elsif ( $opts{task} eq 'instance-schedule-terminate' ) {
        unless ( $opts{instance_id} && $opts{name_equals} ) {
            warn "instance-id and name-equals are required for instance-schedule-terminate task.\n";
            _help();
        }
        _instance_schedule_terminate();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'instance-upgrade' ) {
        if ( $opts{batch} ) {
            unless ( $opts{tenant} && $opts{region} ) {
                warn "tenant (-o) and region (-r) are required for batch instance-upgrade.\n";
                _help();
            }
            _batch_instance_upgrade();
        }
        else {
            unless ( $opts{instance_id} && $opts{tenant} && $opts{region} ) {
                warn "instance-id, tenant, and region are required for instance-upgrade task.\n";
                _help();
            }
            _instance_upgrade();
        }
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'volume-resize' ) {
        unless ( $opts{volume_id} && $opts{region} && $opts{new_size_gbs} ) {
            warn "volume-id, region, and new-size-gbs are required for volume-resize task.\n";
            _help();
        }
        _volume_resize();
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }
    elsif ( $opts{task} eq 'volume-add' ) {
        if ( $opts{batch} ) {
            unless ( $opts{tenant} && $opts{region} ) {
                warn "tenant (-o) and region (-r) are required for batch volume-add.\n";
                _help();
            }
            _batch_volume_add();
        }
        else {
            unless ( $opts{instance_id} && $opts{size_gbs} && $opts{tenant} && $opts{region} && $opts{mount} ) {
                warn "instance-id, size-gbs, tenant, region, and mount are required for volume-add task.\n";
                _help();
            }
            _validate_attach_type( $opts{attach_type} );
            _volume_add();
        }
        if ( $opts{monitor} ) {
            _instance_status();
        }
    }

    print "Operation completed.\n";
}

sub _build_instance_args {
    my ( $options, $mode ) = @_;
    my $json          = JSON::XS->new->utf8;
    my $instance_args = {
        brand  => $options->{brand},
        region => $options->{region},
    };

    if ( $mode eq 'single' ) {
        if ( $options->{owner} ) {
            $instance_args->{owner} = $options->{owner};
        }
        else {
            $instance_args->{owner} = scalar getpwuid($<);
        }
        $instance_args->{final_port_timeout} = 3600;
    }

    $instance_args->{purpose}                 = $options->{purpose}                 if $options->{purpose};
    $instance_args->{panel}                   = $options->{panel}                   if $options->{panel};
    if ( $options->{panel} && $options->{panel} eq 'none' ) {
        $instance_args->{image} = 'alma';
    }
    $instance_args->{hostname}                = $options->{hostname}                if $options->{hostname};
    $instance_args->{customer_phase}          = $options->{customer_phase}          if $options->{customer_phase};
    $instance_args->{subnet_id}               = $options->{subnet_id}               if $options->{subnet_id};
    $instance_args->{ip_primary}              = $options->{ip_primary}              if $options->{ip_primary};
    $instance_args->{shape}                   = $options->{shape}                   if $options->{shape};
    $instance_args->{vcn_name}                = $options->{vcn_name}                if $options->{vcn_name};
    $instance_args->{capacity_reservation_id} = $options->{capacity_reservation_id} if $options->{capacity_reservation_id};
    $instance_args->{availability_domain}     = $options->{availability_domain}     if $options->{availability_domain};
    $instance_args->{ip_count}                = $options->{ip_count}                if defined $options->{ip_count};
    $instance_args->{ip_type}                 = $options->{ip_type}                 if $options->{ip_type};
    $instance_args->{ip_max_per_vnic}         = $options->{ip_max_per_vnic}         if defined $options->{ip_max_per_vnic};
    $instance_args->{ip_mgmt_count}           = $options->{ip_mgmt_count}           if defined $options->{ip_mgmt_count};

    if ( $options->{subtype} eq 'wordpress' ) {
        $instance_args->{server_subtype}  = $options->{subtype};
        $instance_args->{hostname_prefix} = 'wp';
    }

    if ( $options->{brand} ) {
        my $org = $BRAND_ORG_MAP{ $options->{brand} };
        if ( defined $org && ($org eq 'LATAM' || $org eq 'DIRECTI') && $opts{env} eq 'prod' ) {
            $instance_args->{ip_count}      = 5;
            $options->{verify_hosting_site} = 'false';
        }
    }

    if ( $options->{resources_config} ) {
        $instance_args->{resources_config} = $options->{resources_config};
    }

    if ( $options->{volumes_config} ) {
        $instance_args->{volumes_config} = $options->{volumes_config};
    }

    if ( $options->{volumes} ) {
        eval { $instance_args->{volumes} = $json->decode( $options->{volumes} ); }
          or die "Invalid JSON for --volumes: $@\n";
    }

    if ( $options->{ips_secondary} ) {
        eval { $instance_args->{ips_secondary} = $json->decode( $options->{ips_secondary} ); }
          or die "Invalid JSON for --ips-secondary: $@";
    }
    if ( $options->{metadata} ) {
        eval { $instance_args->{metadata} = $json->decode( $options->{metadata} ); }
          or die "Invalid JSON for --metadata: $@";
    }

    if ( $options->{register_hal} ) {
        $instance_args->{register_hal} = ( $options->{register_hal} eq 'true' ? JSON::XS::true : JSON::XS::false );
    }
    if ( $options->{verify_hosting_site} ) {
        $instance_args->{verify_hosting_site} = ( $options->{verify_hosting_site} eq 'true' ? JSON::XS::true : JSON::XS::false );
    }

    if ( $options->{env} eq 'dev' ) {
        if ( defined $options->{auto_delete} ) {
            $instance_args->{auto_delete} = $options->{auto_delete};
        }
        else {
            $instance_args->{auto_delete} = '1h';
        }
    }
    else {
        $instance_args->{hal_watermark_enabled} = JSON::XS::false;
    }

    if ( $options->{instance_config} ) {
        $instance_args->{instance_config} = $options->{instance_config};
    }

    if ( defined $options->{ssh_keys} && $options->{ssh_keys} ne '' ) {
        if ( $options->{ssh_keys} =~ /^\s*\[/ ) {
            eval { $instance_args->{ssh_keys} = $json->decode( $options->{ssh_keys} ); }
              or die "Invalid JSON for --ssh-keys: $@\n";
            die "--ssh-keys JSON must be an array\n"
              unless ref $instance_args->{ssh_keys} eq 'ARRAY';
        }
        else {
            $instance_args->{ssh_keys} = [ $options->{ssh_keys} ];
        }
    }

    return $instance_args;
}

sub _instance_create {
    my $instance_args = _build_instance_args( \%opts, 'single' );

    my $payload = {
        action => 'oci.create_instance',
        args   => $instance_args,
    };

    my $decoded_output = _run_dino_curl( $payload, 'instance-create' );

    if ( $decoded_output && defined $decoded_output->{id} ) {
        if ( $opts{purpose} && $opts{purpose} eq 'migration' ) {
            my $migration_api_host;
            if ( $opts{env} eq 'prod' ) {
                $migration_api_host = 'migration-api.pssh.prod.us-ashburn-1.oci.eigbox.com';
            }
            elsif ( $opts{env} eq 'dev' ) {
                $migration_api_host = 'migration-api.pssh.preprod.us-ashburn-1.oci.eigbox.com';
            }

            if ($migration_api_host) {
                my $migration_payload = {
                    hostname => $opts{hostname},
                    stage    => 'build',
                    task     => 'dino_spawn',
                    status   => 'started',
                    job_id   => $decoded_output->{id},
                };
                if ( $opts{ip_primary} ) {
                    $migration_payload->{destination} = $opts{ip_primary};
                }
                my $json_migration_payload = JSON::XS->new->utf8->encode($migration_payload);
                my $migration_api_url      = "https://$migration_api_host/api/update";
                my $migration_curl_cmd     = sprintf( q{curl -s -X POST -H 'Content-Type: application/json' --data '%s' '%s'}, $json_migration_payload, $migration_api_url );

                _log_message("Executing migration API call: $migration_curl_cmd");
                my $migration_output    = `$migration_curl_cmd`;
                my $migration_exit_code = $? >> 8;

                if ( $migration_exit_code == 0 ) {
                    _log_message("Migration API update successful: $migration_output");
                }
                else {
                    _log_message("Migration API update failed with exit code $migration_exit_code: $migration_output");
                }
            }
        }

        if ( $opts{monitor} ) {
            $opts{job_id}  = $decoded_output->{id};
            $opts{verbose} = 1;
        }
    }
    elsif ( $opts{monitor} && $decoded_output && !defined $decoded_output->{id} ) {
        warn "Could not find 'id' in the instance-create output. Monitoring will not proceed.\n";
    }
}

sub _batch_instance_create {
    my %csv_args = (
        auto_diag           => 2,
        binary              => 1,
        allow_loose_quotes  => 1,
        allow_loose_escapes => 1,
    );

    if ( $Text::CSV_XS::VERSION >= 1.34 ) {
        $csv_args{comment} = "#";
    }

    my $csv = Text::CSV_XS->new( \%csv_args );

    my $csv_file = $opts{batch};
    unless ( -f $csv_file && -r $csv_file ) {
        die "Batch file not found or not readable: $csv_file\n";
    }

    open my $fh, "<:encoding(utf8)", $csv_file or die "Could not open batch file '$csv_file': $!\n";

    my $headers = $csv->getline($fh);
    $csv->column_names(@$headers);

    my @jobs;
    while ( my $row = $csv->getline_hr($fh) ) {
        my %instance_opts = %opts;
        for my $key ( keys %$row ) {
            $instance_opts{$key} = $row->{$key} if defined $row->{$key} and $row->{$key} ne '';
        }

        my $instance_args = _build_instance_args( \%instance_opts, 'batch' );

        my $job = {
            action => 'oci.create_instance',
            args   => $instance_args,
        };
        push @jobs, $job;
    }
    close $fh;

    unless (@jobs) {
        warn "No jobs found in batch file: $csv_file\n";
        return;
    }

    my $json       = JSON::XS->new->utf8;
    my $batch_args = {
        name     => $opts{batch_name} || "batch-create-$$",
        job_type => $opts{batch_job_type},
        size     => $opts{concurrency},
        jobs     => \@jobs,
    };

    $batch_args->{shape} = $opts{shape} if $opts{shape};

    my $payload = {
        action => 'job.batch_migration',
        args   => $batch_args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");

            my $decoded_output = _decode_dino_response( $json, $output, 'batch-create' );
            if ( $decoded_output && defined $decoded_output->{id} ) {
                if ( $opts{monitor} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
            }
            elsif ( $opts{monitor} && $decoded_output && !defined $decoded_output->{id} ) {
                warn "Could not find 'id' in the batch-create output. Monitoring will not proceed.\n";
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _image_create {
    my $json       = JSON::XS->new->utf8;
    my $image_args = {
        region => $opts{region},
        flavor => $opts{flavor},
    };

    $image_args->{brand} = $opts{brand} if $opts{brand};

    if ( defined $opts{set_active} ) {
        $image_args->{set_active} = ( $opts{set_active} eq 'true' ? JSON::XS::true : JSON::XS::false );
    }
    else {
        $image_args->{set_active} = JSON::XS::true;    # default
    }
    $image_args->{verify_image} = ( $opts{verify_image} eq 'true' ? JSON::XS::true : JSON::XS::false );
    if ( defined $opts{update_root_image} ) {
        $image_args->{update_root_image} = ( $opts{update_root_image} eq 'true' ? JSON::XS::true : JSON::XS::false );
    }
    else {
        $image_args->{update_root_image} = JSON::XS::false;    # default
    }

    my $payload = {
        action => 'oci.create_image',
        args   => $image_args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = _decode_dino_response( $json, $output, 'image-create' );
                if ( $decoded_output && defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                elsif ($decoded_output) {
                    warn "Could not find 'id' in the image-create output. Monitoring will not proceed.\n";
                }
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _spawn_create_image {
    my $json       = JSON::XS->new->utf8;
    my $image_args = { flavor => $opts{flavor}, };

    $image_args->{region} = $opts{region} if $opts{region};
    $image_args->{brand}  = $opts{brand}  if $opts{brand};

    if ( defined $opts{force_active} ) {
        $image_args->{force_active} = ( $opts{force_active} eq 'true' ? JSON::XS::true : JSON::XS::false );
    }
    else {
        $image_args->{force_active} = JSON::XS::true;    # default
    }
    $image_args->{verify_image} = ( $opts{verify_image} eq 'true' ? JSON::XS::true : JSON::XS::false );

    my $payload = {
        action => 'oci.spawn_create_image',
        args   => $image_args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = _decode_dino_response( $json, $output, 'spawn-create-image' );
                if ( $decoded_output && defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                elsif ($decoded_output) {
                    warn "Could not find 'id' in the image-create output. Monitoring will not proceed.\n";
                }
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _instance_status {
    my $json = JSON::XS->new->utf8;

    my $job_url = "$DINO_URL/$opts{job_id}";

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'Content-Type: application/json' -H 'Authorization: bearer %s' '%s'\n}, $DINO_JWT, $job_url );
        return;
    }

    my $job_data;

    while (1) {
        $job_data = _dino_http_json(
            method      => 'GET',
            url         => $job_url,
            json        => $json,
            context     => 'instance-status',
            on_fail     => 'fatal',
            max_retries => 3,
            retry_delay => 5,
        );
        unless ( defined $job_data ) {
            warn "Cannot continue instance-status without valid JSON.\n";
            exit 1;
        }

        my $status = $job_data->{status};
        if ( $status eq 'errored' ) {
            _print_batch_summary($job_data);
            _print_batch_child_status_lines($job_data) unless $opts{summary};
            print Dumper($job_data) . "\n" unless $opts{batch_report} || $opts{summary};
            warn "Provisioning failed\n";
            exit 1;
        }
        elsif ( $status =~ /^(?:completed|cancelled)$/ ) {
            _print_batch_summary($job_data);
            _print_batch_child_status_lines($job_data) unless $opts{summary};
            print Dumper($job_data) . "\n" unless $opts{batch_report} || $opts{summary};
            last;
        }

        if ( $opts{verbose} && !$opts{batch_report} ) {
            system 'clear';
            print Dumper($job_data) . "\n";
        }
        elsif ( !$opts{summary} ) {
            print "Current stage: " . ( $job_data->{stage} || 'N/A' ) . "\n";
        }
        _print_batch_summary($job_data);
        _print_batch_child_status_lines($job_data) unless $opts{summary};
        sleep 5;
    }
}

sub _instance_terminate {
    my $json          = JSON::XS->new->utf8;
    my $instance_args = { instance_id => $opts{instance_id}, };

    if ( $opts{tenant} && $opts{region} ) {
        $instance_args->{region} = "$opts{tenant}/$opts{region}";
    }

    my $payload = {
        action => 'oci.instance.terminate',
        args   => $instance_args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = _decode_dino_response( $json, $output, 'instance-terminate' );
                if ( $decoded_output && defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                elsif ($decoded_output) {
                    warn "Could not find 'id' in the instance-terminate output. Monitoring will not proceed.\n";
                }
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _attach_shared_ip {
    my $json    = JSON::XS->new->utf8;
    my $has_ip  = defined $opts{ip}  && $opts{ip}  ne '';
    my $has_ips = defined $opts{ips} && $opts{ips} ne '';

    if ( $has_ip && $has_ips ) {
        die "--ip and --ips are mutually exclusive for attach-shared-ip task.\n";
    }
    if ( !$has_ip && !$has_ips ) {
        die "--ip or --ips is required for attach-shared-ip task.\n";
    }

    my $body = {};
    if ( $has_ip ) {
        $body->{ip_address} = $opts{ip};
    }
    elsif ( $opts{ips} =~ /^\s*\[/ ) {
        my $decoded = eval { $json->decode( $opts{ips} ) };
        die "Invalid JSON for --ips: $@\n" if $@;
        die "--ips JSON must be an array\n" unless ref $decoded eq 'ARRAY';
        $body->{shared_ips} = $decoded;
    }
    else {
        $body->{shared_ips} = $opts{ips};
    }

    $body->{subnet_cidr}     = $opts{subnet_cidr}     if defined $opts{subnet_cidr}     && $opts{subnet_cidr} ne '';
    $body->{ip_max_per_vnic} = $opts{ip_max_per_vnic} if defined $opts{ip_max_per_vnic};
    $body->{ip_mgmt_count}   = $opts{ip_mgmt_count}   if defined $opts{ip_mgmt_count};

    ( my $base = $DINO_URL ) =~ s{/jobs\z}{};
    my $url = "$base/v1/instance/$opts{instance_id}/ip/attach_shared";

    my $decoded = _run_dino_rest_post( $url, $body, 'attach-shared-ip' );
    if ( defined $decoded ) {
        print $json->encode($decoded) . "\n";
    }
}

sub _public_ip_reattach {
    my $json          = JSON::XS->new->utf8;
    my $instance_args = { instance_id => $opts{instance_id}, };
    if ( $opts{tenant} && $opts{region} ) {
        $instance_args->{region} = "$opts{tenant}/$opts{region}";
    }
    if ( $opts{ips} ) {
        eval { $instance_args->{ips} = $json->decode( $opts{ips} ); }
          or die "Invalid JSON for --ips: $@";
    }
    my $payload = {
        action => 'oci.attach_ip',
        args   => $instance_args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = _decode_dino_response( $json, $output, 'public-ip-reattach' );
                if ( $decoded_output && defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                elsif ($decoded_output) {
                    warn "Could not find 'id' in the public-ip-reattach output. Monitoring will not proceed.\n";
                }
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _volume_resize {
    my $json = JSON::XS->new->utf8;

    my $backup_bool = 0;
    if ( $opts{backup} =~ /^(y|yes|true)$/i ) {
        $backup_bool = 1;
    }

    my $args = {
        volume_id    => $opts{volume_id},
        region       => $opts{region},
        new_size_gbs => $opts{new_size_gbs},
        backup       => $backup_bool ? JSON::XS::true : JSON::XS::false,
    };

    my $payload = {
        action => 'volume.grow',
        args   => $args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = _decode_dino_response( $json, $output, 'volume-resize' );
                if ( $decoded_output && defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                elsif ($decoded_output) {
                    warn "Could not find 'id' in the volume-resize output. Monitoring will not proceed.\n";
                }
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _volume_add {
    my $json = JSON::XS->new->utf8;

    my $args = _build_volume_add_args( \%opts );

    my $payload = {
        action => 'volume.create',
        args   => $args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = _decode_dino_response( $json, $output, 'volume-add' );
                if ( $decoded_output && defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                elsif ($decoded_output) {
                    warn "Could not find 'id' in the volume-add output. Monitoring will not proceed.\n";
                }
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _validate_attach_type {
    my ($attach_type) = @_;
    $attach_type = 'paravirtualized' unless defined $attach_type && $attach_type ne '';
    for my $supported_attach_type (@SUPPORTED_ATTACH_TYPES) {
        return $attach_type if $attach_type eq $supported_attach_type;
    }
    warn "Invalid attach-type \"$attach_type\". Supported: @SUPPORTED_ATTACH_TYPES\n";
    exit 1;
}

sub _build_volume_add_args {
    my ($options) = @_;

    my $attach_type = _validate_attach_type( $options->{attach_type} );
    my $args = {
        instance_id => $options->{instance_id},
        size_gbs    => $options->{size_gbs},
        attach_type => $attach_type,
        mount       => $options->{mount},
    };

    my $tenant = $options->{tenant} // '';
    my $region = $options->{region} // '';
    if ( $tenant && $region ) {
        $args->{region} = "$tenant/$region";
    }
    elsif ($region) {
        $args->{region} = $region;
    }

    $args->{display_name} = $options->{display_name} if $options->{display_name};
    return $args;
}

sub _job_restart {
    my $job_run_url = "$DINO_URL/$opts{job_id}/run";

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -X POST -H 'content-type:application/json' -H 'authorization: bearer %s' --data '{}' '%s'\n}, $DINO_JWT, $job_run_url );
    }
    else {
        my $curl_cmd  = sprintf( q{curl -s -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer %s' --data '{}' '%s'}, $DINO_JWT, $job_run_url );
        my $output    = `$curl_cmd`;
        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _instance_schedule_terminate {
    my $json          = JSON::XS->new->utf8;
    my $instance_args = {
        instance_id => $opts{instance_id},
        name_equals => $opts{name_equals},
    };

    $instance_args->{region} = "$opts{tenant}/$opts{region}";

    if ( $opts{expedite} ) {
        $instance_args->{grace_period_days} = 0;
        $instance_args->{low_grace_period}  = JSON::XS::true;
    }

    if ( defined $opts{migration_reset} ) {
        if ( $opts{migration_reset} !~ /^(true|false)$/ ) {
            warn "Invalid value for --migration-reset: \"$opts{migration_reset}\". Valid options are: (true|false)\n";
            _help();
        }
        $instance_args->{migration_reset} = ( $opts{migration_reset} eq 'true' ? JSON::XS::true : JSON::XS::false );
    }

    my $payload = {
        action => 'oci.instance.schedule_terminate',
        args   => $instance_args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        # Use IPC::Run to avoid shell/ARG_MAX issues; send JSON via stdin
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = _decode_dino_response( $json, $output, 'instance-schedule-terminate' );
                if ( $decoded_output && defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                elsif ($decoded_output) {
                    warn "Could not find 'id' in the instance-schedule-terminate output. Monitoring will not proceed.\n";
                }
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _build_instance_upgrade_args {
    my ($options) = @_;
    my $instance_args = {
        instance_id => $options->{instance_id},
    };

    my $tenant = $options->{tenant} // '';
    my $region = $options->{region} // '';
    if ( $tenant && $region ) {
        $instance_args->{region} = "$tenant/$region";
    }
    elsif ($region) {
        $instance_args->{region} = $region;
    }

    $instance_args->{shape}            = $options->{shape}            if $options->{shape};
    $instance_args->{memory}           = $options->{memory}           if $options->{memory};
    $instance_args->{cpu}              = $options->{cpu}              if $options->{cpu};
    $instance_args->{timeout_per_step} = $options->{timeout_per_step} if $options->{timeout_per_step};

    if ( defined $options->{reboot_hard} ) {
        $instance_args->{reboot_hard} = $options->{reboot_hard} ? JSON::XS::true : JSON::XS::false;
    }
    else {
        $instance_args->{reboot_hard} = JSON::XS::true;
    }

    if ( $options->{capacity_reservation_auto} ) {
        $instance_args->{capacity_reservation_auto} =
            $options->{capacity_reservation_auto} eq 'true' ? JSON::XS::true : JSON::XS::false;
    }

    return $instance_args;
}

sub _read_batch_csv_rows {
    my ($csv_file) = @_;
    unless ( -f $csv_file && -r $csv_file ) {
        die "Batch file not found or not readable: $csv_file\n";
    }

    my %csv_args = (
        auto_diag           => 2,
        binary              => 1,
        allow_loose_quotes  => 1,
        allow_loose_escapes => 1,
    );
    if ( $Text::CSV_XS::VERSION >= 1.34 ) {
        $csv_args{comment} = '#';
    }

    my $csv = Text::CSV_XS->new( \%csv_args );
    open my $fh, "<:encoding(utf8)", $csv_file or die "Could not open batch file '$csv_file': $!\n";

    my $headers = $csv->getline($fh);
    die "Batch file '$csv_file' is missing a header row\n" unless $headers && ref $headers eq 'ARRAY' && @$headers;
    $csv->column_names(@$headers);

    my @rows;
    while ( my $row = $csv->getline_hr($fh) ) {
        push @rows, $row;
    }
    close $fh;

    return @rows;
}

sub _batch_instance_upgrade {
    my @rows = _read_batch_csv_rows( $opts{batch} );
    unless (@rows) {
        warn "No jobs found in batch file: $opts{batch}\n";
        return;
    }

    my @jobs;
    for my $row (@rows) {
        my %row_opts = %opts;
        for my $key ( keys %$row ) {
            $row_opts{$key} = $row->{$key} if defined $row->{$key} and $row->{$key} ne '';
        }

        unless ( $row_opts{instance_id} ) {
            die "Each batch row must include instance_id (batch file: $opts{batch})\n";
        }

        my $upgrade_args = _build_instance_upgrade_args( \%row_opts );
        unless ( $upgrade_args->{region} ) {
            die "Each batch row must resolve region via global tenant/region or a row region column\n";
        }

        my $job = {
            action => 'instance.upgrade',
            args   => $upgrade_args,
        };
        if ( $row_opts{hostname} ) {
            $job->{data} = { hostname => $row_opts{hostname} };
        }
        push @jobs, $job;
    }

    my $batch_name = $opts{batch_name} || "batch-upgrade-$$";
    my $json       = JSON::XS->new->utf8;

    if ( $opts{batch_create_only} ) {
        my $create_payload = {
            action => 'job.batch.create',
            args   => {
                name => $batch_name,
                jobs => \@jobs,
            },
        };

        if ( $opts{dry_run} ) {
            _run_dino_curl( $create_payload, 'batch-upgrade-create' );
            return;
        }

        my $create_res = _run_dino_curl( $create_payload, 'batch-upgrade-create' );
        unless ( $create_res && defined $create_res->{id} ) {
            warn "Could not find 'id' in the batch-upgrade-create response.\n";
            exit 1;
        }
        print $json->encode($create_res) . "\n";

        my $expected_children = scalar @jobs;
        my $create_job        = _wait_for_job(
            $json,
            $create_res->{id},
            context => "job.batch.create '$batch_name'",
            timeout => 600,
        );

        my @child_ids = _resolve_batch_child_job_ids( $create_job, $json );
        if ( @child_ids < $expected_children ) {
            die "job.batch.create '$batch_name' completed but only "
              . scalar(@child_ids)
              . " of $expected_children child jobs are visible\n";
        }
        warn "job.batch.create '$batch_name' completed with "
          . scalar(@child_ids)
          . " child job(s) (id=$create_res->{id}).\n";

        if ( $opts{monitor} ) {
            $opts{job_id}  = $create_res->{id};
            $opts{verbose} = 1;
        }
        return;
    }

    my $run_payload = {
        action => 'job.batch.run',
        args   => {
            name           => $batch_name,
            parallel_count => $opts{concurrency},
            jobs           => \@jobs,
        },
    };

    my $run_res = _run_dino_curl( $run_payload, 'batch-upgrade-run' );
    if ( $opts{dry_run} ) {
        return;
    }
    unless ( $run_res && defined $run_res->{id} ) {
        warn "Could not find 'id' in the batch-upgrade-run response.\n";
        exit 1;
    }
    print $json->encode($run_res) . "\n";

    if ( $opts{monitor} ) {
        $opts{job_id}  = $run_res->{id};
        $opts{verbose} = 1;
    }
}

sub _batch_volume_add {
    my @rows = _read_batch_csv_rows( $opts{batch} );
    unless (@rows) {
        warn "No jobs found in batch file: $opts{batch}\n";
        return;
    }

    my @jobs;
    for my $row (@rows) {
        my %row_opts = %opts;
        for my $key ( keys %$row ) {
            $row_opts{$key} = $row->{$key} if defined $row->{$key} and $row->{$key} ne '';
        }

        unless ( $row_opts{instance_id} && $row_opts{size_gbs} && $row_opts{mount} ) {
            die "Each batch row must include instance_id, size_gbs, and mount (batch file: $opts{batch})\n";
        }

        my $volume_add_args = _build_volume_add_args( \%row_opts );
        unless ( $volume_add_args->{region} ) {
            die "Each batch row must resolve region via global tenant/region or a row region column\n";
        }

        my $job = {
            action => 'volume.create',
            args   => $volume_add_args,
        };
        if ( $row_opts{hostname} ) {
            $job->{data} = { hostname => $row_opts{hostname} };
        }
        push @jobs, $job;
    }

    my $batch_name = $opts{batch_name} || "batch-volume-add-$$";
    my $json       = JSON::XS->new->utf8;

    if ( $opts{batch_create_only} ) {
        my $create_payload = {
            action => 'job.batch.create',
            args   => {
                name => $batch_name,
                jobs => \@jobs,
            },
        };

        if ( $opts{dry_run} ) {
            _run_dino_curl( $create_payload, 'batch-volume-add-create' );
            return;
        }

        my $create_res = _run_dino_curl( $create_payload, 'batch-volume-add-create' );
        unless ( $create_res && defined $create_res->{id} ) {
            warn "Could not find 'id' in the batch-volume-add-create response.\n";
            exit 1;
        }
        print $json->encode($create_res) . "\n";

        my $expected_children = scalar @jobs;
        my $create_job        = _wait_for_job(
            $json,
            $create_res->{id},
            context => "job.batch.create '$batch_name'",
            timeout => 600,
        );

        my @child_ids = _resolve_batch_child_job_ids( $create_job, $json );
        if ( @child_ids < $expected_children ) {
            die "job.batch.create '$batch_name' completed but only "
              . scalar(@child_ids)
              . " of $expected_children child jobs are visible\n";
        }
        warn "job.batch.create '$batch_name' completed with "
          . scalar(@child_ids)
          . " child job(s) (id=$create_res->{id}).\n";

        if ( $opts{monitor} ) {
            $opts{job_id}  = $create_res->{id};
            $opts{verbose} = 1;
        }
        return;
    }

    my $run_payload = {
        action => 'job.batch.run',
        args   => {
            name           => $batch_name,
            parallel_count => $opts{concurrency},
            jobs           => \@jobs,
        },
    };

    my $run_res = _run_dino_curl( $run_payload, 'batch-volume-add-run' );
    if ( $opts{dry_run} ) {
        return;
    }
    unless ( $run_res && defined $run_res->{id} ) {
        warn "Could not find 'id' in the batch-volume-add-run response.\n";
        exit 1;
    }
    print $json->encode($run_res) . "\n";

    if ( $opts{monitor} ) {
        $opts{job_id}  = $run_res->{id};
        $opts{verbose} = 1;
    }
}

sub _instance_upgrade {
    my $json          = JSON::XS->new->utf8;
    my $instance_args = _build_instance_upgrade_args( \%opts );

    my $payload = {
        action => 'instance.upgrade',
        args   => $instance_args,
    };

    my $json_payload = $json->encode($payload);

    if ( $opts{dry_run} ) {
        print sprintf( q{curl -s -H 'content-type:application/json' -H 'authorization: bearer %s' --data '%s' '%s'\n}, $DINO_JWT, $json_payload, $DINO_URL );
    }
    else {
        my ( $output, $stderr ) = ( '', '' );

        run [ 'curl', '-s', '-X', 'POST', '-H', 'Content-Type: application/json', '-H', "Authorization: bearer $DINO_JWT", '--data-binary', '@-', $DINO_URL ],
          '<',  \$json_payload,
          '>',  \$output,
          '2>', \$stderr;

        my $exit_code = $? >> 8;

        if ( $exit_code == 0 ) {
            print "$output\n";
            _log_message("command_output: $output");
            if ( $opts{monitor} ) {
                my $decoded_output = _decode_dino_response( $json, $output, 'instance-upgrade' );
                if ( $decoded_output && defined $decoded_output->{id} ) {
                    $opts{job_id}  = $decoded_output->{id};
                    $opts{verbose} = 1;
                }
                elsif ($decoded_output) {
                    warn "Could not find 'id' in the instance-upgrade output. Monitoring will not proceed.\n";
                }
            }
        }
        else {
            warn "Request failed with exit code $exit_code: $output\n";
            _log_message("command_error: $output");
            exit 1;
        }
    }
}

sub _generate_completions {

    my ( $current, $prev ) = @_;
    my @completions;

    my $all_opts =
"-e --env -b --brand -t --task -j --job-id -r --region -o --tenant -d --debug -v --verbose -h --hostname -p --customer-phase -l --panel --flavor --force-active --verify-image --update-root-image -u --purpose -i --ips-secondary --ip --ips -m --metadata -a --auto-delete -x --dry-run -s --subnet-id --subnet-cidr --ip-primary -g --register-hal -y --verify-hosting-site -k --instance-id --shape --resources-config --volumes-config --volumes --instance-config --monitor --vcn-name --expedite --name-equals --capacity-reservation-id --capacity-reservation-auto --availability-domain --batch --batch-name --batch-job-type --batch-create-only --batch-report --summary --concurrency --ip-count --ip-type --memory --cpu --reboot-hard --owner --ip-max-per-vnic --ip-mgmt-count --migration-reset --volume-id --new-size-gbs --backup --size-gbs --attach-type --display-name --mount --timeout-per-step --ssh-keys";

    if ( $prev eq '-e' || $prev eq '--env' ) {
        @completions = @ENVIRONMENTS;
    }
    elsif ( $prev eq '-b' || $prev eq '--brand' ) {
        @completions = @SUPPORTED_BRANDS;
    }
    elsif ( $prev eq '-r' || $prev eq '--region' ) {
        @completions = @SUPPORTED_REGIONS;
    }
    elsif ( $prev eq '-o' || $prev eq '--tenant' ) {
        @completions = @SUPPORTED_TENANTS;
    }
    elsif ( $prev eq '-t' || $prev eq '--task' ) {
        @completions = @TASKS;
    }
    elsif ( $prev eq '-p' || $prev eq '--customer-phase' ) {
        @completions = @CUSTOMER_PHASES;
    }
    elsif ( $prev eq '-l' || $prev eq '--panel' ) {
        @completions = @SUPPORTED_PANELS;
    }
    elsif ( $prev eq '--flavor' ) {
        @completions = @SUPPORTED_FLAVORS;
    }
    elsif ( $prev eq '--shape' ) {
        @completions = @SUPPORTED_SHAPES;
    }
    elsif ( $prev eq '--attach-type' ) {
        @completions = @SUPPORTED_ATTACH_TYPES;
    }
    elsif ( $prev eq '--set-active' || $prev eq '--verify-image' || $prev eq '--force-active' || $prev eq '--update-root-image' || $prev eq '--reboot-hard' || $prev eq '--capacity-reservation-auto' ) {
        @completions = @BOOLEAN_ARGS;
    }
    elsif ( $prev eq '-g' || $prev eq '--register-hal' || $prev eq '--migration-reset' ) {
        @completions = @BOOLEAN_ARGS;
    }
    elsif ( $prev eq '-y' || $prev eq '--verify-hosting-site' ) {
        @completions = @BOOLEAN_ARGS;
    }
    elsif ( $prev eq '--backup' ) {
        @completions = ( 'y', 'n', 'yes', 'no', @BOOLEAN_ARGS );
    }

    # Arguments that take arbitrary values - no specific completions
    elsif ($prev eq '-j'
        || $prev eq '--job-id'
        || $prev eq '-h'
        || $prev eq '--hostname'
        || $prev eq '-u'
        || $prev eq '--purpose'
        || $prev eq '-i'
        || $prev eq '--ips-secondary'
        || $prev eq '--ip'
        || $prev eq '--ips'
        || $prev eq '-m'
        || $prev eq '--metadata'
        || $prev eq '-a'
        || $prev eq '--auto-delete'
        || $prev eq '-s'
        || $prev eq '--subnet-id'
        || $prev eq '--subnet-cidr'
        || $prev eq '--ip-primary'
        || $prev eq '-k'
        || $prev eq '--instance-id'
        || $prev eq '--resources-config'
        || $prev eq '--volumes-config'
        || $prev eq '--volumes'
        || $prev eq '--instance-config'
        || $prev eq '--vcn-name'
        || $prev eq '--name-equals'
        || $prev eq '--capacity-reservation-id'
        || $prev eq '--availability-domain'
        || $prev eq '--batch'
        || $prev eq '--batch-name'
        || $prev eq '--batch-job-type'
        || $prev eq '--concurrency'
        || $prev eq '--ip-count'
        || $prev eq '--ip-type'
        || $prev eq '--memory'
        || $prev eq '--cpu'
        || $prev eq '--timeout-per-step'
        || $prev eq '--ip-max-per-vnic'
        || $prev eq '--ip-mgmt-count'
        || $prev eq '--volume-id'
        || $prev eq '--new-size-gbs'
        || $prev eq '--size-gbs'
        || $prev eq '--display-name'
        || $prev eq '--mount'
        || $prev eq '--ssh-keys' )
    {
        @completions = ();    # Empty array for arbitrary values
    }
    else {
        # If prev is empty (first argument) or current starts with '-', suggest all options
        if ( !defined $prev || $prev eq '' || $current =~ /^-/ ) {
            @completions = split /\s+/, $all_opts;
        }
        else {
            @completions = ();    # No suggestions if it's a value for an unhandled arg
        }
    }

    my @filtered_completions = grep { /\Q$current\E/i } @completions;
    print join ' ', @filtered_completions;
}

__END__

=head1 NAME

oci_server_create.pl - Manage OCI instances via DINO API

=head1 SYNOPSIS

oci_server_create.pl [options]

 Options:
   -e, --env <dev|prod>          Environment (dev or prod).
   -b, --brand <brand>           Brand to operate on. Supported: @SUPPORTED_BRANDS
   -r, --region <region>         Region to operate on. Supported: @SUPPORTED_REGIONS
   -o, --tenant <tenant>         Tenant for region scoping (instance-upgrade and others). Supported: @SUPPORTED_TENANTS
   -t, --task <task>             Task to run (instance-create|instance-status|instance-terminate|job-restart|image-create|spawn-create-image|instance-schedule-terminate|instance-upgrade|volume-resize|volume-add|public-ip-reattach|attach-shared-ip).
   -j, --job-id <id>             Job ID for the task to check (required for instance-status and job-restart).
   --volume-id <id>              Volume ID (required for volume-resize task).
   --new-size-gbs <size>         New size with unit, e.g. 100G (required for volume-resize task).
   --backup <y|n|true|false>     Create backup before resize (volume-resize task). Defaults to n.
   --size-gbs <size>             Volume size in GB (required for volume-add task).
   --attach-type <type>          Attach type: paravirtualized or iscsi (volume-add task). Default: paravirtualized.
   --mount <path>                Mount path for the volume (required for volume-add task).
   --display-name <name>         Optional display name for the volume (volume-add task).
   -h, --hostname <hostname>     Optional hostname for the instance.
   -p, --customer-phase <phase>  Optional customer phase (net-new or migration).
   -l, --panel <panel>           Optional panel for the instance (cpanel, destiny, or none). Defaults to cpanel. panel=none uses the raw alma image (image=alma in payload).
   --ssh-keys <json|key>       Optional SSH public keys for instance-create (JSON array or single key string). Passed to DINO as ssh_keys.
   --flavor <flavor>             Flavor for the image (cpanel or destiny).
   --set-active <true|false>     Set image as active (defaults to true). This is for image-create.
   --force-active <true|false>   Force image active (defaults to true). This is for spawn-create-image.
   --verify-image <true|false>   Verify image after creation (defaults to false).
   --update-root-image <true|false> Update root image (defaults to false).
   -u, --purpose <purpose>       Optional purpose for the instance.
   -i, --ips-secondary <json>    Optional secondary IPs for the instance (e.g., '["1.2.3.4", "5.6.7.8"]').
   --ip <address>                Single shared public IP for attach-shared-ip task.
   --ips <json|csv>              Multiple shared public IPs for attach-shared-ip (JSON array or comma-separated), or optional IPs for public-ip-reattach.
   --subnet-cidr <cidr>          Optional subnet CIDR for attach-shared-ip (when subnet has multiple CIDR blocks).
   -m, --metadata <json>         Optional metadata for the instance (e.g., '{"org": "HOSTGATOR"}').
   -a, --auto-delete <duration>  Optional auto-delete duration for dev instances (e.g., '1h', '30m'). Defaults to '1h'.
   -x, --dry-run                 Dry run (print curl command instead of executing it).
   -s, --subnet-id <id>          Optional subnet ID for the instance. Cannot be used with --vcn-name.
   --ip-primary <ip>             Optional primary IP for the instance.
   --ip-count <int>              Optional number of IPs to attach to the instance.
   --ip-type <type>              Optional type of IP to use for the instance.
   --ip-max-per-vnic <int>       Optional maximum number of IPs per VNIC.
   --ip-mgmt-count <int>         Optional number of management IPs.
   --shape <shape>               Optional OCI shape for the instance.
   --volumes <json>              Optional volumes for the instance (e.g., '[{"name": "data", "size": 100}]').
   --vcn-name <name>             Optional VCN name to use for the instance. Cannot be used with --subnet-id.
   --capacity-reservation-id <id> Optional capacity reservation ID for the instance.
   --availability-domain <digit> Optional availability domain for the instance (single digit).
   --batch <file>              Path to a CSV file for batch instance-create, batch instance-upgrade, or batch volume-add.
   --batch-name <name>         Name for the batch job (stored on child jobs as data.batch.name).
   --batch-job-type <type>     Job type for instance-create batch only (defaults to 'migration').
   --batch-create-only         For instance-upgrade/volume-add batch: submit job.batch.create only (stage children); do not call job.batch.run. Waits for create to complete. Default submits job.batch.run with inline jobs.
   --concurrency <integer>     Parallelism for batch jobs (job.batch.run parallel_count; defaults to 5).
   -g, --register-hal <true|false> Optional flag to register with HAL.
   -y, --verify-hosting-site <true|false> Optional flag to verify hosting site.
   -k, --instance-id <id>        Instance ID (required for single instance-upgrade, instance-terminate, volume-add, public-ip-reattach, attach-shared-ip).
   --memory <integer>          Optional memory for instance upgrade (or per CSV row in batch upgrade).
   --cpu <integer>             Optional CPU count for instance upgrade (or per CSV row in batch upgrade).
   --reboot-hard <true|false>  Optional: hard reboot during instance upgrade (defaults to true).
   --capacity-reservation-auto <true|false>  Optional: auto-use capacity reservation during instance upgrade.
   --timeout-per-step <integer> Optional: timeout in seconds for each upgrade step (defaults to 960).
   --instance-config <config>    Optional instance config to use.
   --expedite                    Optional flag to expedite instance termination (sets grace_period_days to 0 and low_grace_period to true).
   --migration-reset <true|false> Optional: Reset migration status (instance-schedule-terminate task).
   --name-equals <name>          Mandatory for instance-schedule-terminate. Specifies the name of the instance to terminate.
   --owner <owner>               Optional: Override the default owner (defaults to current user).
   --debug                       Enable debug output.
   -v, --verbose                 Verbose output for instance-status.
   --batch-report                For instance-status: for batch parent jobs (job.batch_migration:run, job.batch.create:run, job.batch.run:run), fetch each child job and print job-id,hostname,stage,status,error (CSV). Uses instance_id when hostname is absent. Suppresses parent Data::Dumper output for readability.
   --summary                     For instance-status on batch parent jobs: print progress (counts, rate, ETA) to stderr from data.batch.status. Parent poll only; no child job fetches. Supersedes --batch-report when both are set.
   --help                        Print this help message.
   --complete                    Internal option for bash completion.
   --current <word>              Internal option for bash completion.
   --prev <word>                 Internal option for bash completion.

=head1 DESCRIPTION

This script interacts with the DINO API to manage OCI instances, including
creating, upgrading, checking status, and terminating instances.

Batch instance-upgrade CSV columns: instance_id (required per row); optional
cpu, memory, shape, hostname, tenant, region (row values override global flags).

Batch volume-add CSV columns: instance_id, size_gbs, mount (required per row);
optional attach_type, display_name, hostname, tenant, region (row values
override global flags).

=cut
