#!/opt/bin/perl

=head1 NAME

anyevent-mcp-form-elicitation - display an MCP elicitation form

=head1 SYNOPSIS

   anyevent-mcp-form-elicitation <request.json >response.json

=head1 DESCRIPTION

Reads one UTF-8 JSON object containing MCP form elicitation parameters:
C<mode> (optional, C<form>), C<message> and C<requestedSchema>. Displays
the form using the shared local UI, preferring Tk, ANSI on the controlling
terminal, ANSI in a separate terminal, then the plain terminal interface.
Writes one ordinary MCP response to stdout:

   {"action":"accept","content":{"answer":"Some text"}}
   {"action":"decline"}
   {"action":"cancel"}

Exit status zero means a valid response, including decline or cancel.
Nonzero means invalid input or helper failure; diagnostics go to stderr.
Closing a working dialog cancels the question, without fallback.

Forms contain at most 32 fields. Supported field types are strings,
single-select string enums (C<enum> or titled C<oneOf> values), multi-select
string enums (arrays with C<items.enum> or C<items.anyOf>), booleans, numbers
and integers. Titles, descriptions, defaults, required fields, length and
selection bounds are supported. Unsupported schema features, including string
formats, nested objects and URL elicitation, produce an error.

Text fields accept multiline answers. Optional unselected choices,
booleans and blank numbers are omitted; empty text is returned as an empty
string. Optional arrays have a separate inclusion checkbox. Invalid
answers are explained and the entered values retained for correction.

The helper does not speak an MCP transport or maintain continuation tokens.
It can be used directly from shell scripts or replaced by another executable
with the same stdin/stdout contract. MCP callers use
C<PERL_ANYEVENT_MCP_ELICITATION_HELPER> to select an alternative.

=head1 OPTIONS

=over

=item --tk

Use only Tcl/Tk.

=item --ansi

Use only full-screen ANSI on C</dev/tty>. Ctrl-N inserts a newline in
multiline fields while editing.

=item --xterm-ansi

Use ANSI in a separate terminal emulator.

=item --tty

Use only the plain terminal interface on C</dev/tty>. Enter keeps a field's
value, C<:clear> clears text, C<<< << >>> enters multiline text ending with
a line containing only C<.>, and C<:cancel> cancels.

=item --help

Print usage and exit.

=back

See L<anyevent-mcp-askpermission> for interface configuration.

=cut

use common::sense;
use Types::Serialiser ();
use Getopt::Long ();
use Scalar::Util qw(looks_like_number);
use AnyEvent::MCP ();
use AnyEvent::MCP::UI ();

my %modes;
Getopt::Long::GetOptions
   (map { $_ => \$modes{$_} } qw(tty tk ansi xterm-ansi)),
   "help" => \my $help,
   or exit 2;

!@ARGV or die "Unexpected arguments\n";
my @modes = grep $modes{$_}, keys %modes;
@modes <= 1 or die "Prompt modes are mutually exclusive\n";

if ($help) {
   print "usage: $0 [--tk | --ansi | --xterm-ansi | --tty] <request.json >response.json\n";
   exit;
}

binmode STDIN;
binmode STDOUT;
my $json = AnyEvent::MCP::json->canonical;
my $input = "";
while (read STDIN, my $chunk, 8192) {
   $input .= $chunk;
   length $input <= 1 << 20 or die "Form request exceeds 1 MiB\n";
}

my $params = AnyEvent::MCP::decode_json $input;

sub value {
   my ($field, $value) = @_;

   my $name = $field->{name};
   if ($field->{type} eq "boolean") {
      Types::Serialiser::is_bool ($value) or die "$name: expected a boolean\n";
   } elsif ($field->{type} eq "array") {
      ref $value eq "ARRAY" or die "$name: expected an array\n";
      @$value >= ($field->{minItems} || 0) or die "$name: too few selections\n";
      !defined $field->{maxItems} || @$value <= $field->{maxItems} or die "$name: too many selections\n";
      my %choices = map { $_->{value} => 1 } @{$field->{choices}};
      my %seen;
      !grep { !defined || ref || !$choices{$_} || $seen{$_}++ } @$value
         or die "$name: unknown or duplicate choice\n";
   } elsif ($field->{type} eq "string") {
      defined $value && !ref $value or die "$name: expected text\n";
      length $value >= ($field->{minLength} || 0) or die "$name: text is too short\n";
      !defined $field->{maxLength} || length $value <= $field->{maxLength} or die "$name: text is too long\n";
      !exists $field->{choices} || grep $_->{value} eq $value, @{$field->{choices}}
         or die "$name: unknown choice\n";
   } else {
      defined $value && !ref $value && looks_like_number $value
         && $value !~ /nan|inf/i or die "$name: expected a number\n";
      $value = 0 + $value;
      "$value" !~ /nan|inf/i or die "$name: expected a finite number\n";
      $field->{type} ne "integer" || $value == int $value or die "$name: expected an integer\n";
      !defined $field->{minimum} || $value >= $field->{minimum} or die "$name: below minimum\n";
      !defined $field->{maximum} || $value <= $field->{maximum} or die "$name: above maximum\n";

      return 0 + $value;
   }
   $value
}

sub fields {
   my ($params) = @_;

   ref $params eq "HASH" && (!defined $params->{mode} || $params->{mode} eq "form")
      or die "Only form elicitation is supported\n";
   defined $params->{message} && !ref $params->{message}
      or die "Elicitation needs a message\n";
   my $schema = $params->{requestedSchema};
   ref $schema eq "HASH" && $schema->{type} eq "object" && ref $schema->{properties} eq "HASH"
      or die "Elicitation needs a flat object schema\n";
   !grep !/\A(?:type|properties|required|\$schema)\z/, keys %$schema
      or die "Unsupported form schema keyword\n";
   keys %{$schema->{properties}} <= 32 or die "Too many form fields\n";
   !exists $schema->{required} || ref $schema->{required} eq "ARRAY"
      or die "Invalid required fields\n";
   my %required;
   for (@{$schema->{required} || []}) {
      defined && !ref && exists $schema->{properties}{$_} or die "Unknown required field\n";
      $required{$_} = 1;
   }

   my @fields;
   for my $name (sort keys %{$schema->{properties}}) {
      my $field = $schema->{properties}{$name};
      ref $field eq "HASH" && $field->{type} =~ /\A(?:string|number|integer|boolean|array)\z/
         or die "Unsupported field type for $name\n";
      my %allowed = map { $_ => 1 } qw(type title description default);
      $allowed{$_} = 1 for $field->{type} eq "string" ? qw(minLength maxLength enum oneOf) :
         $field->{type} eq "boolean" ? () : $field->{type} eq "array" ? qw(items minItems maxItems) : qw(minimum maximum);
      !grep !$allowed{$_}, keys %$field or die "Unsupported schema keyword for $name\n";
      for (qw(title description)) {
         !exists $field->{$_} || defined $field->{$_} && !ref $field->{$_}
            or die "Invalid $_ for $name\n";
      }
      my $copy = { %$field, name => $name, required => $required{$name} };
      my $enum = $field;
      my $titled = exists $field->{oneOf};
      if ($field->{type} eq "array") {
         $enum = $field->{items};
         ref $enum eq "HASH" or die "Invalid array items for $name\n";
         $titled = exists $enum->{anyOf};
         ($titled ? keys %$enum == 1
            : keys %$enum == 2 && $enum->{type} eq "string" && exists $enum->{enum})
            or die "Only multi-select string enums supported for $name\n";
      }

      if ($field->{type} eq "array" || exists $enum->{enum} || $titled) {
         !(exists $enum->{enum} && $titled) or die "Conflicting enums for $name\n";
         my $items = $titled ? ($field->{type} eq "array" ? $enum->{anyOf} : $enum->{oneOf}) : $enum->{enum};
         ref $items eq "ARRAY" && @$items && @$items <= 256 or die "Invalid enum for $name\n";
         my %seen;
         $copy->{choices} = [map {
            my ($v, $label);
            if ($titled) {
               ref $_ eq "HASH" && !grep !/\A(?:const|title)\z/, keys %$_
                  or die "Invalid titled enum for $name\n";
               ($v, $label) = ($_->{const}, $_->{title} // $_->{const});
            } else {
               ($v, $label) = ($_, $_);
            }
            defined $v && !ref $v && defined $label && !ref $label && !$seen{$v}++
               or die "Invalid enum value for $name\n";
            +{ value => $v, label => $label }
         } @$items];
      }
      for (qw(minLength maxLength minItems maxItems)) {
         !exists $field->{$_} || defined $field->{$_} && !ref $field->{$_}
            && $field->{$_} =~ /\A[0-9]+\z/ or die "Invalid $_ for $name\n";
      }
      for (qw(minimum maximum)) {
         !exists $field->{$_} || defined $field->{$_} && !ref $field->{$_}
            && looks_like_number $field->{$_} && $field->{$_} !~ /nan|inf/i
               or die "Invalid $_ for $name\n";
      }
      !defined $field->{minLength} || !defined $field->{maxLength}
         || $field->{minLength} <= $field->{maxLength} or die "Invalid length bounds for $name\n";
      !defined $field->{minItems} || !defined $field->{maxItems}
         || $field->{minItems} <= $field->{maxItems} or die "Invalid selection bounds for $name\n";
      !defined $field->{minimum} || !defined $field->{maximum}
         || $field->{minimum} <= $field->{maximum} or die "Invalid numeric bounds for $name\n";
      value ($copy, $field->{default}) if exists $field->{default};
      push @fields, $copy;
   }
   \@fields
}

sub response {
   my ($params, $response) = @_;

   my $fields = fields $params;
   ref $response eq "HASH" or die "Invalid elicitation response\n";
   my $action = $response->{action};
   return { action => $action } if defined $action && ($action eq "decline" || $action eq "cancel");
   defined $action && $action eq "accept" && ref $response->{content} eq "HASH"
      or die "Invalid elicitation response action\n";
   my %known = map { $_->{name} => 1 } @$fields;
   !grep !$known{$_}, keys %{$response->{content}} or die "Unknown response field\n";
   my %content;
   for my $field (@$fields) {
      my $name = $field->{name};
      if (exists $response->{content}{$name}) {
         $content{$name} = value ($field, $response->{content}{$name});
      } else {
         !$field->{required} or die "$name: required field is missing\n";
      }
   }
   { action => "accept", content => \%content }
}

# escape terminal controls without interpreting markup or form field syntax.
sub visible {
   my $text = shift;

   $text =~ s/([\x00-\x08\x0b-\x1f\x7f-\x9f\x{202a}-\x{202e}\x{2066}-\x{2069}])/sprintf "\\u{%X}", ord $1/ge;
   $text
}

my $fields = fields $params;
for my $field (@$fields) {
   $field->{choices} = [
      { label => "No", value => Types::Serialiser::false },
      { label => "Yes", value => Types::Serialiser::true },
   ] if $field->{type} eq "boolean";
}

sub initial {
   my ($field) = @_;

   if ($field->{type} eq "array") {
      return $field->{required} ? "" : undef unless exists $field->{default};
      my %selected = map { $_ => 1 } @{$field->{default}};
      return join " ", map $_ + 1, grep $selected{$field->{choices}[$_]{value}}, 0 .. $#{$field->{choices}};
   }
   return $field->{choices} ? 1 : "" unless exists $field->{default};
   if ($field->{choices}) {
      my $default = $json->encode ($field->{default});
      for (0 .. $#{$field->{choices}}) {
         return $_ + 2 if $json->encode ($field->{choices}[$_]{value}) eq $default;
      }
   }
   $field->{default}
}

sub contents {
   my ($raw) = @_;

   my %content;
   for my $i (0 .. $#$fields) {
      my $field = $fields->[$i];
      my $value = $raw->[$i];
      if ($field->{type} eq "array") {
         next unless defined $value;
         my @indices = split " ", $value;
         !grep { !/\A[1-9][0-9]*\z/ || $_ > @{$field->{choices}} } @indices
            or die "$field->{name}: invalid selection\n";
         $value = [map $field->{choices}[$_ - 1]{value}, @indices];
      } elsif ($field->{choices}) {
         defined $value && $value =~ /\A[0-9]+\z/ && $value <= @{$field->{choices}} + 1
            or die "$field->{name}: invalid selection\n";
         next if $value < 2;
         $value = $field->{choices}[$value - 2]{value};
      } elsif ($field->{type} ne "string") {
         next if !defined $value || $value eq "";
      }
      $content{$field->{name}} = $value;
   }
   response ($params, { action => "accept", content => \%content })
}

my $ui = AnyEvent::MCP::UI->new (mode => $modes[0]);
my @raw = map initial ($_), @$fields;
my $error = "";
while (1) {
   my (%values, @widgets);
   for my $i (0 .. $#$fields) {
      my $field = $fields->[$i];
      my $name = "f$i";
      my $title = visible ($field->{title} // $field->{name});
      $title .= " *" if $field->{required};
      push @widgets, [label => {text => visible ($field->{description}), role => "caption"}]
         if length $field->{description};

      if ($field->{type} eq "array") {
         push @widgets, [label => {text => $title, role => "section"}];
         unless ($field->{required}) {
            $values{"${name}_include"} = defined $raw[$i] ? 1 : 0;
            push @widgets, [check => {name => "${name}_include", label => "Include this field"}];
         }
         my %selected = map { $_ => 1 } split " ", $raw[$i];
         for my $j (0 .. $#{$field->{choices}}) {
            $values{"${name}_$j"} = $selected{$j+1} ? 1 : 0;
            push @widgets, [check => {name => "${name}_$j", label => visible ($field->{choices}[$j]{label})}];
         }
      } elsif ($field->{choices}) {
         $values{$name} = $raw[$i];
         push @widgets, [choice => {name => $name, label => $title, choices => [
            [1, "(no selection)"],
            map [$_+2, ($_+1) . ": " . visible ($field->{choices}[$_]{label})], 0 .. $#{$field->{choices}},
         ]}];
      } else {
         $values{$name} = $raw[$i];
         push @widgets, [entry => {name => $name, label => $title,
            multiline => $field->{type} eq "string" ? 1 : 0,
            (defined $field->{maxLength} ? (max => $field->{maxLength}) : ())}];
      }
   }

   my ($action, $selected) = $ui->dialog (
      title => "MCP form",
      default => "accept",
      values => \%values,
      body => [vbox => {},
         [label => {text => "MCP form", role => "heading"}],
         (length $error ? [label => {text => visible ($error), role => "danger"}] : ()),
         [vbox => {scroll => 1, expand => 1},
            [label => {text => visible ($params->{message})}],
            @widgets,
         ],
         [hbox => {},
            [button => {action => "decline", label => "Decline", expand => 1}],
            [button => {action => "cancel", label => "Cancel", expand => 1}],
            [button => {action => "accept", label => "Submit", role => "primary", expand => 1}],
         ],
      ],
   );
   my $response;
   if (!defined $action || $action eq "cancel") {
      $response = {action => "cancel"};
   } elsif ($action eq "decline") {
      $response = {action => "decline"};
   } elsif ($action eq "accept") {
      @raw = map {
         my $i = $_;
         my $field = $fields->[$i];
         $field->{type} eq "array"
            ? ($field->{required} || $selected->{"f${i}_include"}
               ? join (" ", map $_+1, grep $selected->{"f${i}_$_"}, 0 .. $#{$field->{choices}})
               : undef)
            : $selected->{"f$i"}
      } 0 .. $#$fields;
      $response = eval { contents \@raw };
      if ($@) {
         $error = $@;
         next;
      }
   } else {
      die "Invalid form action\n";
   }
   print AnyEvent::MCP::encode_json ($response), "\n";
   last;
}
