#!/usr/bin/env perl
# SPDX-FileCopyrightText: 2025 Jonathan Poelen <jonathan.poelen@gmail.com>
# SPDX-License-Identifier: MIT

my $file = "";

open(my $input, '<:encoding(UTF-8)', $ARGV[0])
  or die "Could not open file '$ARGV[0]': $!";

open(my $output, '>:encoding(UTF-8)', $ARGV[1])
  or die "Could not open file '$ARGV[1]': $!";

while (<$input>)
{
  $file .= $_;
}

$warning = "\n\n<!-- ***** THIS FILE WAS GENERATED BY A SCRIPT - DO NOT EDIT ***** -->\n";
$last_context = "
  <context name='FindComment' lineEndContext='#pop' attribute='Style_Normal'>
    <StringDetect String='//' context='CommentSingle'/>
    <StringDetect String='/*' context='CommentMultiLine'/>
  </context>

  <context name='CommentSingle' lineEndContext='#pop' attribute='Style_Comment'>
    <DetectSpaces/>
    <IncludeRules context='##Comments'/>
    <DetectIdentifier/>
  </context>

  <context name='CommentMultiLine' lineEndContext='#stay' attribute='Style_Comment'>
    <IncludeRules context='CommentSingle'/>
    <StringDetect String='*/' context='#pop' attribute='Style_Comment'/>
  </context>
";
$last_item = "<itemData name='Style_Comment' defStyleNum='dsComment' />";

$language = $file =~ s#.*?(<language[^>]+?>).*#$1#sr;
$language =~ s#name="[^"]+#name="JSONC" priority="1#s;
$language =~ s#extensions="[^"]+#extensions="*.json;*.jsonc#s;
$language =~ s#mimetype="[^"]+#mimetype="application/json#s;
$language =~ s/version="([^"]+)/sprintf("version=\"%d", $1-9)/se;
$language =~ s/kateversion="([^"]+)/kateversion="5.0/s;
$file =~ s#<!-- JSONC -->#<IncludeRules context="FindComment"/>#sg;
$file =~ s#<language[^>]+?>#$warning\n$language#s;
$file =~ s#</itemDatas>#$last_item\n</itemDatas>#s;
$file =~ s#</contexts>#$last_context</contexts>#s;

print $output $file;
print $output $warning;
