#!/usr/bin/perl

# ./stringtoxml.pl --tags "Anime/RPG" --tags "Anime/Isekai" --tags "Anime/Tensei" --tags "Manhwa/Isekai" --tags "Manhwa/Tensei" --tags "Manhwa/RPG" --tags "Manga/RPG" --tags "Manga/Isekai" --tags "Manga/Tensei" --tags "1/22/333" > output.xml
# cat output.xml | sed 's/^[ \t]*//' | sed ':a;N;$!ba;s/\n//g' > output_minify.xml

use strict;
use warnings;

my $MAX_TAGS = 100;

my %root_nodes;
my %root_tags;

my @atags = ();
while (my $arg = shift @ARGV) {
    if ($arg eq '--tags') {
        my $atags_arg = shift @ARGV;
        push @atags, split /,/, $atags_arg;
    }
}

foreach my $tag (@atags) {
    my @levels = split /\//, $tag;
    my $current_node = undef;
    foreach my $i (0 .. $#levels) {
        my $level = $levels[$i];
        if (!defined $current_node) {
            if (!exists $root_tags{$level}) {
                $root_nodes{$level} = {
                    tag => $level,
                    level => $i,
                    children => [],
                    num_children => 0
                };
                $root_tags{$level} = 1;
                $current_node = $root_nodes{$level};
            } else {
                foreach my $node (values %root_nodes) {
                    if ($node->{tag} eq $level) {
                        $current_node = $node;
                        last;
                    }
                }
            }
        } else {
            my $found = 0;
            foreach my $child (@{$current_node->{children}}) {
                if ($child->{tag} eq $level) {
                    $current_node = $child;
                    $found = 1;
                    last;
                }
            }
            if (!$found) {
                push @{$current_node->{children}}, {
                    tag => $level,
                    level => $i,
                    children => [],
                    num_children => 0
                };
                $current_node = $current_node->{children}[-1];
            }
        }
    }
}

print "<Categories>\n";
print_xml(values %root_nodes);
print "</Categories>\n";

sub print_xml {
    foreach my $node (@_) {
        print "  " x $node->{level} . "  <Category Assigned=\"1\">$node->{tag}\n";
        if (@{$node->{children}}) {
            print_xml(@{$node->{children}});
        }
        print "  " x ($node->{level} + 1) . "</Category>\n";
    }
}

