#!/usr/bin/env raku

use JSON::Infer;

#| Retrieve JSON from a URL
multi sub MAIN(Str :$uri!, Str :$out-dir = "lib", Str :$class-name!, Bool :$kebab ) {
    CATCH {
        when X::Infer {
            note $_.message;
            exit 5;
        }
    }
    my $infer = JSON::Infer.new;
    my JSON::Infer::Class $class = $infer.infer(:$uri, :$class-name, :$kebab);
    save-class($class, $out-dir);
}

#| Infer JSON from a file
multi sub MAIN(Str :$file!, Str :$out-dir = "lib", Str :$class-name!, Bool :$kebab ) {

    CATCH {
        when X::Infer {
            note $_.message;
            exit 5;
        }
    }


    my $infer = JSON::Infer.new;

    my JSON::Infer::Class $class = $infer.infer(:$file, :$class-name, :$kebab);

    save-class($class, $out-dir);
}

my sub save-class(JSON::Infer::Class $class, Str $out-dir = 'lib' ) {
    my IO::Path $base-dir = do if $out-dir.IO.is-relative {
        $*CWD.add($out-dir);
    }
    else {
        $out-dir.IO;
    }

    my $out-file = $base-dir.add($class.file-path);

    my $parent = $out-file.parent;

    if not $parent.d {
        $parent.mkdir;
    }

    my $out = $out-file.open(:w);

    $out.print($class.make-class);
    $out.close;
}


# vim: expandtab shiftwidth=4 ft=raku
