#!/opt/bin/perl

=head1 NAME

anyevent-mcp-askpermission - graphical or terminal permission helper

=head1 DESCRIPTION

Ask whether an MCP tool may perform an operation. Displays the operation,
requested authority and reason, with choices to allow or deny once or save
a rule for future requests.

The bundled helper is normally invoked by the server, not directly by
the user. It reads one UTF-8 JSON offer on stdin and writes one semantic
decision on stdout. See L<AnyEvent::MCP::Permissions::Helper>.

Without an explicit interface, the helper tries Tk, ANSI on C</dev/tty>,
ANSI in a separate terminal, then the plain terminal interface. Closing
a prompt or encountering a failure after it starts denies the request.
The helper never delegates permission authority to the MCP client.

The rule editor offers the server's named scopes, sandbox grants and
lifetimes. Scope and grant settings affect future matching rules, not
the authority requested by this operation. Details are display-only and
never become rule constraints. Closing the prompt denies once.
Return on an ordinary permission prompt allows once if the denial message
is blank (only whitespace), otherwise denies once with the message.
Critical permission dialogs have no Return action; select a decision explicitly.

=head1 OPTIONS

=over

=item --manage-rules FILE

Display saved rules in evaluation order and allow deletion or reordering.
Expired rules are marked. The editor does not require the application's
sandbox grant registry. Invalid file syntax is reported as an error.
Changes fail if the list changed elsewhere. Can select an interface.

=item --edit-rules FILE

Edit the original permission rule file using C<$VISUAL>, C<$EDITOR>,
C<sensible-editor> or C<vi>. Does not validate or overwrite editor output.
Cannot combine with other options selecting a UI or rule management.

=item --tk

Use Tcl/Tk only. An installed Alien::Tclsh is preferred to system Tcl.
C<PERL_ANYEVENT_MCP_TCLSH> overrides executable discovery.
C<PERL_ANYEVENT_MCP_THEME> selects C<auto>, C<light> or C<dark>.
On X11 the automatic theme checks the C<anyevent-mcp.theme> resource,
then the desktop portal.
The C<anyevent-mcp.scale> resource adjusts the Tk interface size relative
to its normal size, without changing Tk's display DPI. For example:

   anyevent-mcp.scale: 0.85

The scale defaults to 1.0 and must be positive and finite. On X11,
the XENVIRONMENT file (or ~/.Xdefaults-HOSTNAME) is also read.
Window placement belongs to the window manager.

=item --ansi

Use a full-screen ANSI dialog on C</dev/tty>. Requires Term::ReadKey.
Tab and arrow keys navigate controls; Space or Return selects them.
Page Up/Down scroll; Escape cancels. Mouse interaction is supported.

=item --xterm-ansi

Open ANSI in a separate terminal emulator (C<x-terminal-emulator>,
then C<xterm>, or C<PERL_ANYEVENT_MCP_TERMINAL>). The emulator must
support C<-T TITLE -e PROGRAM ARGUMENTS...> and wait for its child.

=item --tty

Use a plain terminal on C</dev/tty>. No full-screen sequences or optional
terminal dependencies. Enter retains a field value; explicit numbered
choices select actions.

=item --form

Adapt the permission request to standard MCP elicitation forms using
C<PERL_ANYEVENT_MCP_ELICITATION_HELPER> or the bundled form helper.
An explicit interface forces the corresponding built-in form renderer.
Completes all stages locally and returns one semantic decision.

=item --help

Print usage and exit.

=back

=cut

use common::sense;
use Getopt::Long ();
use Text::ParseWords ();
use AnyEvent::MCP ();
use AnyEvent::MCP::Permissions::Ask ();
use AnyEvent::MCP::Permissions::Dialog ();
use AnyEvent::MCP::Server::Permissions ();
use AnyEvent::MCP::UI ();

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

my @modes = grep $modes{$_}, keys %modes;
@ARGV || defined $rules_file && defined $edit_file
   and die "Unexpected arguments\n";
@modes > 1 and die "Prompt modes are mutually exclusive\n";
(defined $edit_file && (@modes || $form)) || defined $rules_file && $form
   and die "Incompatible options\n";

if ($help) {
   print "usage: $0 [--tk | --ansi | --xterm-ansi | --tty] [--form | --manage-rules FILE | --edit-rules FILE]\n";
   exit;
}

binmode STDIN, ":raw";
binmode STDOUT, ":raw";

my $json = AnyEvent::MCP::json->canonical;
my $ui = AnyEvent::MCP::UI->new (mode => $modes[0]);
my $form_job;
$SIG{TERM} = $SIG{INT} = sub {
   $form_job->cancel if $form_job;
   exit 1;
};

sub manage_rules {
   my ($file) = @_;

   my $permissions = AnyEvent::MCP::Server::Permissions->new;
   $permissions->{file} = $file;
   my $error = "";
   my $index = 1;

   while (1) {
      my ($rules) = $permissions->_read_rules (1);
      $index = @$rules if $index > @$rules;
      $index ||= 1;
      my @rows = map {
         my $i = $_ + 1;
         my $rule = $rules->[$_];
         my $expiry = $rule->{expires};
         my $when = !defined $expiry ? "Never"
            : $expiry =~ /\A[0-9]{1,12}\z/ ? ($expiry <= time ? "(expired)" : do {
               my @t = localtime $expiry;
               sprintf "%04d-%02d-%02d %02d:%02d", $t[5]+1900, $t[4]+1, @t[3,2,1]
            }) : "Invalid expiry";
         my $scope = join "; ", map {
            my $key = $_;
            $key =~ s/^match\.//;
            "$key=$rule->{$_}"
         } sort grep !/\A(?:decision|action|tool|sandbox-grants|expires)\z/, keys %$rule;
         ["$i", "$i", map AnyEvent::MCP::Permissions::Dialog::display ($_),
            $rule->{decision} // "", $rule->{action} // "", $rule->{tool} // "*", $rule->{"sandbox-grants"} // "", $scope, $when]
      } 0 .. $#$rules;
      my ($action, $values) = $ui->dialog (
         title => "MCP permission rules",
         default => "close",
         focus => "index",
         width => 1260,
         values => {index => $index},
         body => [vbox => {},
            [label => {text => "Saved rules (" . @$rules . ") - first matching unexpired rule wins", role => "heading"}],
            [label => {text => $file, role => "mono"}],
            (length $error ? [label => {text => $error, role => "danger"}] : ()),
            (@rows ? [list => {name => "index", label => "Select rule", scroll => 1, expand => 1,
               columns => [["#", 4], ["Decision", 8], ["Action", 9], ["Tool", 15],
                  ["Capabilities", 28], ["Scope / conditions", 36], ["Expires", 17]],
               rows => \@rows, lines => @$rules < 20 ? scalar @$rules : 20,
            }] : [label => {text => "No saved rules."}]),
            [hbox => {},
               [button => {action => "close", label => "Close"}],
               (@rows ? (
                  [button => {action => "view", label => "View selected rule"}],
                  [button => {action => "up", label => "Move up"}],
                  [button => {action => "down", label => "Move down"}],
                  [button => {action => "delete", label => "Delete selected", explicit => 1, role => "danger"}],
               ) : ()),
            ],
         ],
      );
      return unless defined $action && $action ne "close";
      $index = $values->{index};
      next unless $index =~ /\A[1-9][0-9]*\z/ && $index <= @$rules;
      if ($action eq "view") {
         $ui->dialog (
            title => "MCP permission rule $index", default => "back", width => 1000,
            body => [vbox => {},
               [label => {text => "Rule $index of " . @$rules, role => "heading"}],
               [text => {text => AnyEvent::MCP::Config::serialize_ini ([["rule", $rules->[$index-1]]]),
                  mono => 1, lines => 16, scroll => 1, expand => 1}],
               [hbox => {}, [button => {action => "back", label => "Back"}]],
            ],
         );
         next;
      }
      next if $action eq "up" && $index == 1;
      next if $action eq "down" && $index == @$rules;
      my $expected = $json->encode ($rules);

      $error = "";
      eval {
         my $lock = $permissions->_lock;
         my ($current, $preferences) = $permissions->_read_rules (1);
         die "Permission rules changed since selection\n"
            unless $json->encode ($current) eq $expected;
         if ($action eq "delete") {
            splice @$current, $index - 1, 1;
         } elsif ($action eq "up" || $action eq "down") {
            my $other = $action eq "up" ? $index - 2 : $index;
            @$current[$index - 1, $other] = @$current[$other, $index - 1];
            $index = $other + 1;
         } else {
            die "Invalid rule management action\n";
         }

         $permissions->_write ($current, $preferences);
         1
      } or $error = $@;
   }
}

sub edit_rules {
   my ($file) = @_;

   my $permissions = AnyEvent::MCP::Server::Permissions->new;
   $permissions->{file} = $file;
   my $lock = $permissions->_lock; # ensure the file exists and is private.
   close $lock or die "Cannot unlock permission rules: $!\n";

   for my $choice (grep { defined && /\S/ } @ENV{qw(VISUAL EDITOR)}, "sensible-editor", "vi") {
      my @editor = Text::ParseWords::shellwords ($choice);
      next unless @editor;

      my $status = system { $editor[0] } @editor, AnyEvent::MCP::utf8enc ($file);
      next if $status == -1;

      $status == 0
         or die "Editor failed or was interrupted (status $status)\n";

      return
   }

   die "No editor found (VISUAL, EDITOR, sensible-editor, vi)\n"
}
if (defined $rules_file) {
   eval { manage_rules AnyEvent::MCP::utf8dec $rules_file; 1 } or do {
      print STDERR $@;
      exit 1;
   };
   exit;
}

if (defined $edit_file) {
   eval { edit_rules AnyEvent::MCP::utf8dec $edit_file; 1 } or do {
      print STDERR $@;
      exit 1;
   };
   exit;
}

my $request = do { local $/; AnyEvent::MCP::decode_json (scalar <STDIN>) };
$request->{version} == 1
   or die "Invalid permission request\n";

sub form_dialog {
   my $stage = "choice";
   my $previous = {};
   while (1) {
      $form_job = AnyEvent::MCP::Helper->new (
         helper => @modes
            ? ["anyevent-mcp-form-elicitation", "--$modes[0]"]
            : $ENV{PERL_ANYEVENT_MCP_ELICITATION_HELPER} || "anyevent-mcp-form-elicitation",
      );
      my $cv = AE::cv;
      $form_job->ask (AnyEvent::MCP::Permissions::Ask::form ($request, $stage, $previous), sub { $cv->send (@_) });
      my ($success, $response) = $cv->recv;
      undef $form_job;
      $success or die "$response\n";

      my $answer = AnyEvent::MCP::Permissions::Ask::decision ($request, $response, $stage, $previous);
      if ($stage eq "choice" && $answer->{decision} =~ /-always\z/) {
         $stage = "rule";
         $previous = $answer;
      } elsif ($answer->{decision} eq "back") {
         $stage = "choice";
      } else {
         return $answer
      }
   }
}

my $decision = eval {
   $form ? form_dialog : AnyEvent::MCP::Permissions::Dialog::prompt ($ui, $request)
};
if ($@) {
   print STDERR "Permission prompt failed; denied: $@";
   $decision = { decision => "deny-once" };
}
print AnyEvent::MCP::encode_json ($decision), "\n";
