#!/opt/bin/perl

=head1 NAME

anyevent-mcp - initialize MCP configuration and manage users and permissions

=head1 SYNOPSIS

   anyevent-mcp init
   anyevent-mcp manage-rules fs-default
   anyevent-mcp create-user chatgpt
   anyevent-mcp revoke-user chatgpt
   anyevent-mcp edit-rules-file /path/to/rules.ini
   anyevent-mcp ui-demo tk

=head1 DESCRIPTION

C<anyevent-mcp> sets up the shared AnyEvent::MCP configuration and manages
permission rules saved by its servers. Use it to review permissions you have
allowed or denied permanently, remove a rule, or change the order in which
rules are checked.

C<manage-rules> opens a graphical rule manager; C<edit-rules> opens the
rule file in your text editor. Both take a rule profile name. For example,
C<anyevent-mcp manage-rules fs-default> manages the default filesystem
server's rules. The corresponding C<*-file> commands accept a pathname
when an application stores its rules elsewhere.

C<init> ensures the private global configuration contains a persistent
master secret, from which servers derive their connection credentials.
You normally do not need to run it: servers initialize their global
configuration automatically. Repeating C<init> leaves an existing secret
unchanged.

See L<AnyEvent::MCP::Intro> for setting up and connecting to the servers,
L<AnyEvent::MCP/GLOBAL CONFIGURATION> for the configuration file format,
and L<AnyEvent::MCP::Server::Permissions/RULE FILES> for permission rules.

=head1 COMMANDS

=over

=item init

Ensure that the private global configuration and master secret exist.
An existing secret is preserved; missing secrets are generated and saved.
C<--config FILE> selects a different configuration file for this command.

=item manage-rules NAME

Open the rule deletion and reordering interface for the named profile.
For a filesystem server started with C<--name code>, use profile C<fs-code>.

=item edit-rules NAME

Open the named profile's rule file in a text editor.

=item manage-rules-file $file

Open the rule manager for the explicit pathname C<$file>.

=item edit-rules-file $file

Open C<$file> in a text editor. Use these explicit-file commands for
applications whose rule files do not use the named-profile convention.

=item ui-demo [MODE [CASE]]

Try a simulated permission dialog, including its rule editor, with no
actual request or rule changes. CASE is C<patch> (default), C<read>,
C<exec>, C<script> or C<critical>. C<widgets> displays the general widget
showcase, including multiline input.
MODE is C<auto> (default), C<tk>, C<ansi>, C<xterm-ansi> or C<tty>.
Here C<auto> selects a local interface, never an MCP client.
Prints the selected renderer and result as JSON on stdout.
No server, configuration or permission rule changes are involved.
See L<anyevent-mcp-askpermission> for UI configuration and environment variables.

=item create-user USER

Enable a new named user; rotate a revoked user at the next generation.
Use --program or --instance for a scoped override.

=item revoke-user USER

Disable a user, preserving the generation for later rotation. In a narrower
scope, a negative definition also blocks inherited credentials. Implicit
global:default is revocable. Restart affected servers after changes; these
commands do not print secrets. Use server --print-url[=USER] for URLs.

User commands rewrite the selected INI file in canonical form. Existing
settings are retained, but comments and formatting are not preserved.

=back

Named profiles use
C<anyevent-mcp/rules/NAME.ini> in the user configuration directory.
Editing uses C<$VISUAL>, C<$EDITOR>, C<sensible-editor> or C<vi>.
For server URLs, use each server's C<--print-url> option.

=head1 OPTIONS

=over

=item --config FILE

Use FILE instead of default global configuration
(C<$XDG_CONFIG_HOME/anyevent-mcp/global.ini>, or
C<~/.config/anyevent-mcp/global.ini>). Relevant to C<init> and user
management; rule management uses its own profile or pathname.

=item --program NAME

Select C<[program NAME]> for user management.

=item --instance NAME

Select C<[instance NAME]> for user management. Cannot combine with --program.

=item --help

Print command synopsis, available commands and configuration defaults,
then exit without running a command.

=back

=cut

use common::sense;

use Getopt::Long ();

use AnyEvent::MCP ();
use AnyEvent::MCP::Config ();

sub usage {
   print <<'EOF';
Usage: anyevent-mcp [OPTIONS] COMMAND [ARGUMENTS]

   manage-rules NAME       delete/reorder rules
   edit-rules NAME         edit rules with VISUAL, EDITOR, sensible-editor, vi
   manage-rules-file FILE  manage an explicit rules file
   edit-rules-file FILE    edit an explicit rules file
   ui-demo [MODE [CASE]]  try a permission dialog (auto, tk, ansi, xterm-ansi, tty)
                         cases: patch (default), read, exec, script, critical, widgets
   init                    create a private configuration and master secret
   create-user USER        enable or rotate a managed user
   revoke-user USER        revoke a managed user

Options (before COMMAND):
   --config FILE           use a different global configuration file
   --program NAME          select [program NAME] for user management
   --instance NAME         select [instance NAME] for user management
   --help                  show this help

User definitions inherit from [global] through [program NAME] to
[instance NAME]; narrower scopes override wider ones. Without --program
or --instance, user commands modify [global]. Revoked users remain
disabled until recreated with a new token generation. The implicit
global:default user is enabled initially.

Examples:
   anyevent-mcp create-user chatgpt
   anyevent-mcp --program mcp-fs create-user backup
   anyevent-mcp --instance private revoke-user alice
   anyevent-mcp revoke-user chatgpt
   mcp-multibroker --print-urls        # list all enabled user URLs
   mcp-multibroker --print-url=chatgpt # show just chatgpt's URL

Server changes take effect after restart. The selected connect_user
(default: default) authenticates auxiliary browser/Vim/reverse connections.

Rule profiles are stored under $XDG_CONFIG_HOME/anyevent-mcp, falling back
to ~/.config/anyevent-mcp/rules (e.g. manage-rules fs-default).

Configuration defaults to ~/.config/anyevent-mcp/global.ini, or the
corresponding location under XDG_CONFIG_HOME. Use --help for this text.

A missing master secret is generated and saved automatically when a server
loads its configuration. Configuration format: see AnyEvent::MCP.
EOF
}

sub change_user {
   my ($file, $section, $user, $command) = @_;

   my $lock = AnyEvent::MCP::file_lock $file;
   my $config = AnyEvent::MCP::Config->new (file => $file)->load ($lock);
   my $values = $config->{section}{$section} ||= {};
   my $key = "user.$user";
   my $generation = $values->{$key};
   if (defined $generation) {
      $generation =~ /\A-?[1-9][0-9]*\z/ && length $generation < 18
         or die "Invalid $key generation '$generation'\n";
      $generation = 0 + $generation;
   }

   if ($command eq "create-user") {
      die "$key already enabled in [$section]\n"
         if defined $generation && $generation > 0 || !defined $generation && $section eq "global" && $user eq "default";
      $generation = defined $generation ? -$generation + 1 : 1;
   } else {
      die "$key already revoked in [$section]\n" if defined $generation && $generation < 0;
      if (!defined $generation) {
         ($section ne "global" || $user eq "default")
            or die "$key is not enabled\n";
         $generation = -1;
      } else {
         $generation = -$generation;
      }
   }

   $values->{$key} = $generation;
   $config->save;
   close $lock or die "$file: $!\n";
   print "$section: $user generation " . abs ($generation)
      . ($generation > 0 ? " enabled\n" : " revoked\n");
}

sub permission_demo {
   my ($ui, $case) = @_;
   $case =~ /\A(?:read|patch|exec|script|critical)\z/
      or die "Invalid demo case: $case\n";

   require AnyEvent::MCP::Permissions::Dialog;
   my $workdir = "/home/alice/src/project";
   my $offer = {
      version => 1, program => "mcp-fs", name => "demo", multibroker_alias => "example-fs",
      action => "write", tool => "file-patch", selected_workdir => $workdir,
      action_description => "Modify existing resources",
      reason => "Update the documentation and regression tests (simulated request).",
      sandbox_implementation => "bubblewrap",
      sandbox_grants => [qw(workdir-write host-network)],
      sandbox_grant_closure => [qw(workdir-read workdir-write host-network)],
      sandbox_grant_choices => [qw(workdir-read workdir-write homedir-read host-network long-running)],
      sandbox_grant_descriptions => {
         "workdir-read" => "Read files within the selected workdir and its subdirectories.",
         "workdir-write" => "Create, modify, rename and delete files in the selected workdir, including any existing files below it. Implies workdir-read.",
         "homedir-read" => "Read files throughout the host user's home directory.",
         "host-network" => "Access the host network, including local services.",
         "long-running" => "Permit commands to run longer than the ordinary time limit.",
      },
      dimension_order => ["workdir"],
      dimensions => {
         workdir => {label => "Workdir", value => $workdir, default => "exact", choices => [
            {id => "exact", label => "This workdir: $workdir"},
            {id => "any", label => "Any configured workdir, including future ones"},
         ]},
      },
      decisions => [qw(deny-once deny-always allow-always allow-once)],
      lifetimes => [map {+{value => $_->[0], label => $_->[1]}} ["indefinite", "Indefinite"],
         ["900", "15 minutes"], ["3600", "1 hour"], ["57600", "16 hours"]],
      lifetime_default => "900",
      lifetime_max => 365 * 86400,
      paths => [map "$workdir/$_", "README.md", "doc/usage.md", "lib/Example.pm", "t/usage.t", "t/permissions.t", "t/fixtures/sample.txt"],
      details => {"View patch" => "File: $workdir/README.md\n\n@@ -1 +1 @@\n-Old heading\n+New heading\n"},
   };
   if ($case eq "read") {
      @$offer{qw(tool action action_description reason sandbox_grants sandbox_grant_closure paths details)}
         = ("file-read", "read", "Read file contents", "Read the project README.",
            ["workdir-read"], ["workdir-read"], ["$workdir/README.md"], {});
   } elsif ($case eq "exec" || $case eq "script") {
      my $argv = $case eq "exec" ? ["prove", "-Ilib", "t/permissions.t"]
                                : ["sh", "-c", join ("\n", map "# Step $_\nprintf '%s\\n' 'example $_'", 1..22)];
      @$offer{qw(tool action action_description reason context paths details)}
         = ("exec", "exec", "Execute a command", "Run project checks.",
            {argv => $argv, stdin_bytes => 18, stdin_encoding => "utf-8"}, [],
            {"View stdin" => "Sample input data\n"});
      my $command = AnyEvent::MCP::json->encode ($argv);
      my $command_label = length $command > 100 ? substr ($command, 0, 97) . "..." : $command;
      $offer->{dimensions}{subject} = {
         label => "Command", value => $command, default => "command",
         choices => [{id => "command", label => "Exact command: $command_label"},
            {id => "executable", label => "This executable: $argv->[0] (any arguments)"},
            {id => "any", label => "Any command"}],
      };
   } elsif ($case eq "critical") {
      @$offer{qw(tool action action_description reason critical sandbox_grants sandbox_grant_closure paths details)}
         = ("workdir-add", "admin", "Change available authority", "Make another directory available.",
            1, [], [], ["/home/alice/another-project"], {});
   } else {
      $offer->{dimensions}{subject} = {
         label => "File", value => $offer->{paths}[0], default => "exact",
         choices => [{id => "exact", label => "This file: $offer->{paths}[0]"}, {id => "any", label => "Any file"}],
      };
   }

   my $answer = AnyEvent::MCP::Permissions::Dialog::prompt ($ui, $offer, 1);
   my $renderer = $ui->{mode} || lc ((split /::/, ref $ui->{ui})[-1]);
   print AnyEvent::MCP::encode_json ({renderer => $renderer, %$answer}), "\n";
}

sub ui_demo {
   my ($mode, $case) = @_;
   $mode ||= "auto";
   $mode =~ /\A(?:auto|tk|ansi|xterm-ansi|tty)\z/
      or die "Invalid UI mode: $mode\n";

   require AnyEvent::MCP::UI;
   my $ui = AnyEvent::MCP::UI->new (mode => $mode eq "auto" ? undef : $mode);
   $case ||= "patch";
   if ($case ne "widgets") {
      permission_demo $ui, $case;
      return;
   }
   my ($action, $values) = $ui->dialog (
      title => "MCP UI demo",
      default => "cancel",
      focus => "name",
      values => {
         name => "Example", notes => "First line\nSecond line",
         enabled => 1, extra => 0, choice => "blue",
      },
      body => [vbox => {},
         [label => {text => "ANYEVENT::MCP    /    WIDGET DEMO", role => "eyebrow"}],
         [label => {text => "Try the interface", role => "heading"}],
         [label => {text => "All controls are real widgets; the result is only printed as JSON.", role => "caption"}],
         [vbox => {scroll => 1, expand => 1},
            [vbox => {style => "panel"},
               [label => {text => "INPUT FIELDS", role => "section"}],
               [entry => {name => "name", label => "Single line (max. 40 characters)", max => 40}],
               [entry => {name => "notes", label => "Multiline text", multiline => 1}],
               [choice => {name => "choice", label => "Choose a color", choices => [
                  [blue => "Blue"], [green => "Green"], [red => "Red"],
                  [unicode => "Unicode: \x{3c0} \x{65e5}\x{672c}\x{8a9e}"],
               ]}],
               [check => {name => "enabled", label => "Initially checked"}],
               [check => {name => "extra", label => "Initially unchecked"}],
            ],
            [vbox => {style => "panel"},
               [label => {text => "READ-ONLY TEXT", role => "section"}],
               [label => {text => "Normal label, including Unicode: \x{3c0} \x{65e5}\x{672c}\x{8a9e}."}],
               [label => {text => "Monospaced label: 0123456789 ABCDEF", role => "mono"}],
               [text => {text => join ("\n", map sprintf ("%02d  The quick brown fox jumps over the lazy dog.", $_), 1..16),
                  lines => 4, mono => 1, wrap => "none"}],
               [detail => {label => "Open detail viewer", text => join ("\n", map "Detail line $_", 1..40)}],
            ],
            [label => {text => "Example warning", role => "warning"}],
            [vbox => {style => "alert"},
               [label => {text => "Example danger message. Nothing is actually at risk.", role => "danger"}],
            ],
         ],
         [label => {text => "Explicit action needs a click or focused Space (a numbered choice in plain TTY).", role => "caption"}],
         [hbox => {},
            [button => {action => "cancel", label => "Cancel", expand => 1}],
            [button => {action => "explicit", label => "Explicit action", role => "danger", explicit => 1, expand => 1}],
            [button => {action => "submit", label => "Submit", role => "primary", expand => 1}],
         ],
      ],
   );
   my $renderer = $ui->{mode} || lc ((split /::/, ref $ui->{ui})[-1]);
   print AnyEvent::MCP::encode_json ({renderer => $renderer, action => $action, values => $values}), "\n";
}

Getopt::Long::Configure ("no_auto_abbrev", "no_ignore_case", "require_order");
Getopt::Long::GetOptions
   "config=s"   => \my $file,
   "program=s"  => \my $program,
   "instance=s" => \my $instance,
   "help"       => \my $help,
   or exit 2;

if ($help) {
   usage;
   exit 0;
}

my $command = shift @ARGV;
unless (defined $command) {
   usage;
   exit 2;
}

@ARGV = map AnyEvent::MCP::utf8dec $_, @ARGV;

eval {
   if ($command =~ /\A(?:manage-rules|edit-rules)(?:-file)?\z/ && @ARGV == 1) {
      my $path = $ARGV[0];
      if ($command !~ /-file\z/) {
         $path =~ /\A[A-Za-z0-9][A-Za-z0-9_.-]*\z/
            or die "Invalid permission rule profile name\n";
         my $config_home = $ENV{XDG_CONFIG_HOME} || ($ENV{HOME} || die "HOME is not set\n") . "/.config";
         $config_home =~ m{\A/} or die "XDG_CONFIG_HOME must be an absolute path\n";
         $path = "$config_home/anyevent-mcp/rules/$path.ini";
      }
      my $action = $command =~ /\Amanage-/ ? "--manage-rules" : "--edit-rules";
      exec "anyevent-mcp-askpermission", $action, AnyEvent::MCP::utf8enc $path;
      die "Cannot start permission rule tool: $!\n";
   } elsif ($command eq "ui-demo" && @ARGV <= 2) {
      ui_demo @ARGV;
   } elsif ($command eq "init" && !@ARGV) {
      my $config = AnyEvent::MCP::Config::global_config (defined $file ? (file => $file) : ());
      print "Initialized $config->{file}\n";
   } elsif ($command =~ /\A(?:create-user|revoke-user)\z/ && @ARGV == 1) {
      !defined $program || !defined $instance or die "--program and --instance are exclusive\n";
      my $user = AnyEvent::MCP::Config::user_name ($ARGV[0]);
      my $scope = defined $program ? "program " . AnyEvent::MCP::instance_name ($program)
                : defined $instance ? "instance " . AnyEvent::MCP::instance_name ($instance)
                : "global";
      my $config_file = $file // AnyEvent::MCP::Config::_file ();
      AnyEvent::MCP::Config->new (file => $config_file)->load->ensure_secret;
      change_user $config_file, $scope, $user, $command;
   } else {
      die "Invalid command or arguments; use --help\n";
   }
   1
} or do {
   print STDERR $@;
   exit 1;
};

