#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use Config::IniFiles;
use LWP::UserAgent;
use JSON;
use Digest::MD5 qw(md5_hex);
use Data::Dumper;
use utf8;
use Encode;

# Global debug flag
my $DEBUG = 1;  # Set to 0 to disable debugging

binmode STDOUT, ':encoding(UTF-8)';
binmode STDERR, ':encoding(UTF-8)';

my $ua = LWP::UserAgent->new;
my $cgi = CGI->new;

sub debug_print {
    print STDERR @_ if $DEBUG;
}

sub call_rpc {
    my ($method, $params, $config) = @_;
    my @keys = ($method eq "end_conversation") 
        ? qw(id project_id token)
        : qw(id project_id token conversation_timeout config_url);
    
    $params->{$_} = $config->{$_} for @keys;
    
    my $request = {
        jsonrpc => "2.0",
        method => $method,
        params => $params,
        id => 1
    };
    
    my $response = $ua->post(
        $config->{url},
        Content_Type => 'application/json',
        Content => encode_json($request)
    );

    debug_print("REQ: " . encode_json($request) . "\n\n");
    debug_print("RES: " . Dumper($response) . "\n\n");

    return $response;
}

sub load_config {
    my $number = shift;
    $number =~ s/[^\d]+//g;
    my $cfg = Config::IniFiles->new(-file => "/var/www/configs/$number.cnf")
        or die "Failed to read configuration file: " . Config::IniFiles->error();
    
    my $config = { map { $_ => $cfg->val('settings', $_) } $cfg->Parameters('settings') };
    debug_print("CFG for $number: " . Dumper($config) . "\n\n");
    return $config;
}

sub process_request {
    my ($body, $to, $from) = map { decode('UTF-8', $cgi->param($_) || '') } qw(Body To From);
    my $config = load_config($to);
    $config->{id} = md5_hex($from . $to);
    $config->{conversation_timeout} ||= "3600";

    my $response = (($body eq "+end") || ($body eq "/end") || ((lc($body) eq "please end the conversation.")))
        ? call_rpc("end_conversation", {}, $config)
        : call_rpc("chat", {message => $body}, $config);

    my $ai_response = "Error communicating with AI service";
    if ($response->is_success) {
        my $result = decode_json($response->content);
        $ai_response = $result->{result}{response} || $result->{result}{status};
    }

    return $ai_response;
}

my $ai_response = process_request();
$ai_response =~ s/\n/
/g;

print $cgi->header('text/xml charset=UTF-8');
print qq{<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Message>$ai_response</Message>
</Response>
};

# Debugging information
# ... (add any necessary debug prints here)