#                                     Copyright 2025 WebPros International, LLC
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
package Common::JSONC;

use cPstrict;
use File::Slurper ();
use JSON::XS      ();

=encoding utf8

=head1 NAME

Common::JSONC

=head1 DESCRIPTION

Common functions to handle JSONC (JSON with comments) files loading

=head1 FUNCTIONS

=cut

=head2 strip_comments($jsonc)

Strip the comments from a JSON encoded content.

=head3 ARGUMENTS

=over

=item $jsonc - string

JSON encoded content that may contain comments.

=back

=head3 RETURNS

JSON encoded content without comments.

=cut

sub strip_comments ($jsonc) {
    $jsonc =~ s{/\*.*?\*/}{}gs;    # Remove multi-line comments
    $jsonc =~ s{//.*?$}{}gm;       # Remove single-line comments
    return $jsonc;
}

=head2 load_jsonc($file)

=head3 ARGUMENTS

=over

=item $file - string

Path to the JSONC file to load.

=back

=head3 RETURNS

Parsed JSON content.

=head3 THROWS

=over

=item When the file does not exist.

=item When the file does not contain valid JSON.

=back

=cut

sub load_jsonc ($file) {

    my $jsonc = eval { File::Slurper::read_text($file) }
      or die "Cannot load file $file with error: $!";

    my $json_stripped = strip_comments($jsonc);
    my $json          = eval { JSON::XS::decode_json($json_stripped) }
      or die "Cannot parse JSONC $file with error: $@";

    return $json;
}

1;
