#!/usr/bin/perl

use strict;
use warnings;
use lib qw/lib/;
use Urb::Dom;
use Urb::Dom::Fitness;
use File::Spec;
use YAML;
use Carp;

my $overlay = undef;
if (-e 'occlusion.field')
{
    say STDERR 'Using occlusion overlay field';
    $overlay = Urb::Field::Occlusion->new;
    open my $YAML, '<', 'occlusion.field' or croak "$!";
    my $string = join '', (<$YAML>);
    close $YAML;
    $overlay->Deserialise ($string);
}

my $config = undef;
my $path_patterns = File::Spec->catfile (File::Spec->updir(), 'patterns.config');
if (-e $path_patterns)
{
    say STDERR 'Using project level patterns config file';
    $config = YAML::LoadFile ($path_patterns);
}
if (-e 'patterns.config')
{
    say STDERR 'Using patterns config file';
    my $config_temp = YAML::LoadFile ('patterns.config');
    for my $key (keys %{$config_temp})
    {
        $config->{$key} = $config_temp->{$key};
    }
}

my $costs = undef;
my $path_costs = File::Spec->catfile (File::Spec->updir(), 'costs.config');
if (-e $path_costs)
{
    say STDERR 'Using project level costs config file';
    $costs = YAML::LoadFile ($path_costs);
}
if (-e 'costs.config')
{
    say STDERR 'Using costs config file';
    my $costs_temp = YAML::LoadFile ('costs.config');
    for my $key (keys %{$costs_temp})
    {
        $costs->{$key} = $costs_temp->{$key};
    }
}

my $assessor = Urb::Dom::Fitness->new ($config, $costs);

my $first = 1;

for my $path_yaml (@ARGV)
{
    my $dom0 = Urb::Dom->new;
    $dom0->Deserialise (YAML::LoadFile ($path_yaml));

    if ($first)
    {
        $assessor->{_occlusion} = $dom0->Occlusion ($overlay);
        $assessor->{_occlusion}->{nocache} = 1;
    }
    undef $first;

    my $dom1 = $dom0->Clone;
    my $dom2 = $dom0->Clone;
    my $dom3 = $dom0->Clone;

    $dom0->Straighten_Recursive (0);
    $dom1->Straighten_Recursive (1);
    $dom2->Straighten_Recursive (2);
    $dom3->Straighten_Recursive (3);
    my @sorted = sort {$assessor->_apply ($a) <=> $assessor->_apply ($b)} ($dom0, $dom1, $dom2, $dom3);

    my $dom = pop @sorted;
    YAML::DumpFile ($path_yaml, $dom->Serialise);
}

0;
