package Games::ABC_Path::Generator;
$Games::ABC_Path::Generator::VERSION = '0.6.0';
use 5.006;

use strict;
use warnings;

use integer;

use parent 'Games::ABC_Path::Generator::Base';

use Games::ABC_Path::Solver::Constants;
use Games::ABC_Path::Solver::Board '0.1.0';
use Games::ABC_Path::MicrosoftRand             ();
use Games::ABC_Path::Generator::RiddleObj      ();
use Games::ABC_Path::Generator::FinalLayoutObj ();
use Games::ABC_Path::Generator::Coord          ();


sub _init
{
    my $self = shift;
    my $args = shift;

    $self->{seed} = $args->{seed};

    $self->{rand} =
        Games::ABC_Path::MicrosoftRand->new( seed => $self->{seed} );

    return;
}

sub _shuffle
{
    my ( $self, $deck ) = @_;

    return $self->{'rand'}->shuffle($deck);
}

{
    my @get_next_cells_lookup = (
        map {
            my $start = Games::ABC_Path::Generator::Coord->_from_int($_);
            [
                map {
                    my ( $y, $x ) =
                        ( $start->y() + $_->[$Y], $start->x() + $_->[$X] );
                    (
                        (
                                   __PACKAGE__->_x_in_range($x)
                                && __PACKAGE__->_y_in_range($y)
                        ) ? ( __PACKAGE__->_xy_to_int( [ $y, $x ] ) ) : ()
                    )
                } (
                    [ -1, -1 ], [ -1, 0 ],  [ -1, 1 ], [ 0, -1 ],
                    [ 0,  1 ],  [ 1,  -1 ], [ 1,  0 ], [ 1, 1 ]
                )
            ]
        } ( 0 .. $BOARD_SIZE - 1 )
    );

    sub _get_next_cells
    {
        my ( $self, $l, $init_idx ) = @_;

        return [ grep { vec( $l, $_, 8 ) == 0 }
                @{ $get_next_cells_lookup[$init_idx] } ];
    }
}

sub _add_next_state
{
    my ( $self, $stack, $l, $cell_int ) = @_;

    vec( $l, $cell_int, 8 ) = 1 + @$stack;

    push @$stack,
        [ $l, $self->_shuffle( $self->_get_next_cells( $l, $cell_int ) ) ];

    return;
}

sub _get_num_connected
{
    my ( $self, $l ) = @_;

    my @connectivity_stack = ( index( $l, "\0" ) );

    my %connected;
    while (@connectivity_stack)
    {
        my $int = pop(@connectivity_stack);
        if ( !$connected{$int}++ )
        {
            push @connectivity_stack,
                ( grep { !exists( $connected{$_} ) }
                    @{ $self->_get_next_cells( $l, $int ) } );
        }
    }

    return scalar keys %connected;
}


sub calc_final_layout
{
    my $self = shift;

    my @dfs_stack;
    $self->_add_next_state( \@dfs_stack, '',
        $self->{rand}->max_rand($BOARD_SIZE) );

DFS:
    while (@dfs_stack)
    {
        my ( $l, $last_cells ) = @{ $dfs_stack[-1] };

        if ( @dfs_stack == $BOARD_SIZE )
        {
            return Games::ABC_Path::Generator::FinalLayoutObj->new(
                { layout_string => $l, }, );
        }

# print "Depth = " . scalar(@dfs_stack) . "\n";
# print "Last state = " . Dumper($last_state) . "\n";
# print "Layout = \n" . $self->get_layout_as_string($last_state->{layout}) . "\n";

        my $next_idx = shift(@$last_cells);

        if (
            ( !defined($next_idx) )
            or ( $self->_get_num_connected($l) !=
                ( $BOARD_SIZE - scalar(@dfs_stack) ) )
            )
        {
            pop(@dfs_stack);
        }
        else
        {
            $self->_add_next_state( \@dfs_stack, $l, $next_idx );
        }
    }

    die "Not found!";
}


sub _gen_clue_positions
{
    my ( $self, $cb ) = @_;
    return [ map { $cb->($_) } $self->_x_indexes() ];
}

sub _calc_clue_positions
{
    my $self = shift;
    return [
        map {
            [ map { $self->_xy_to_int($_) }
                    @{ $self->_gen_clue_positions($_) } ]
        } (
            sub { [ $_, $_ ]; },
            sub { [ $_, 4 - $_ ]; },
            (
                map {
                    my $y = $_;
                    sub { [ $y, $_ ] };
                } $self->_y_indexes()
            ),
            (
                map {
                    my $x = $_;
                    sub { [ $_, $x ] };
                } $self->_x_indexes()
            ),
        )
    ];
}

my @_clues_positions = @{ __PACKAGE__->_calc_clue_positions() };

sub calc_riddle
{
    my ($self) = @_;

    my $layout = $self->calc_final_layout();

    my $A_pos = $layout->get_A_pos;

    my %init_state = (
        pos_taken => '',
        clues     => [ map { +{ num_remaining => 5, } } ( 1 .. $NUM_CLUES ), ]
    );

    my $mark = sub {
        my ( $state, $pos ) = @_;

        vec( $state->{pos_taken}, $pos, 1 ) = 1;

        my $coord = Games::ABC_Path::Generator::Coord->_from_int($pos);

        foreach my $clue (
            ( ( $coord->y == $coord->x )             ? 0 : () ),
            ( ( $coord->y == ( 5 - 1 ) - $coord->x ) ? 1 : () ),
            ( 2 + $coord->y ),
            ( ( 2 + 5 ) + $coord->x ),
            )
        {
            $state->{clues}->[$clue]->{num_remaining}--;
        }
    };

    $mark->( \%init_state, $A_pos );

    my @dfs_stack = ( \%init_state );

DFS:
    while (@dfs_stack)
    {
        my $last_state = $dfs_stack[-1];

        if ( !exists( $last_state->{chosen_clue} ) )
        {
            my @clues = (
                sort {
                    ( $a->[1]->{num_remaining} <=> $b->[1]->{num_remaining} )
                        or ( $a->[0] <=> $b->[0] )
                    }
                    grep { !exists( $_->[1]->{cells} ) }
                    map  { [ $_, $last_state->{clues}->[$_] ] }
                    ( 0 .. $NUM_CLUES - 1 )
            );

            if ( !@clues )
            {
                # Yay! We found a configuration.
                my $handle_clue = sub {
                    my @cells = @{ shift->{cells} };
                    return [ map { $layout->get_cell_contents($_) }
                            @{ $self->_shuffle( \@cells ) } ];
                };
                my $riddle = Games::ABC_Path::Generator::RiddleObj->new(
                    {
                        solution => $layout,
                        clues    => [
                            map { $handle_clue->($_) } @{ $last_state->{clues} }
                        ],
                        A_pos => Games::ABC_Path::Generator::Coord->_from_int(
                            $A_pos),
                    }
                );

                my $riddle_string = $riddle->get_riddle_v1_string();

                my $solver =
                    Games::ABC_Path::Solver::Board->input_from_v1_string(
                    $riddle_string);

                $solver->solve();

                if ( @{ $solver->get_successes_text_tables() } != 1 )
                {
                    # The solution is ambiguous
                    pop(@dfs_stack);
                    next DFS;
                }
                else
                {
                    return $riddle;
                }
            }

            # Not enough for the clues there.
            if ( $clues[0][1]->{num_remaining} < 2 )
            {
                pop(@dfs_stack);
                next DFS;
            }

            my $clue_idx = $clues[0][0];

            $last_state->{chosen_clue} = $clue_idx;

            my @positions =
                ( grep { !vec( $last_state->{pos_taken}, $_, 1 ) }
                    @{ $_clues_positions[$clue_idx] } );

            my @pairs;

            foreach my $first_idx ( 0 .. $#positions - 1 )
            {
                foreach my $second_idx ( $first_idx + 1 .. $#positions )
                {
                    push @pairs, [ @positions[ $first_idx, $second_idx ] ];
                }
            }

            $last_state->{pos_pairs} = $self->_shuffle( \@pairs );
        }

        my $chosen_clue = $last_state->{chosen_clue};
        my $next_pair   = shift( @{ $last_state->{pos_pairs} } );

        if ( !defined($next_pair) )
        {
            pop(@dfs_stack);
            next DFS;
        }

        my %new_state;
        $new_state{pos_taken} = $last_state->{pos_taken};
        $new_state{clues} = [ map { +{ %{$_} } } @{ $last_state->{clues} } ];
        foreach my $pos (@$next_pair)
        {
            $mark->( \%new_state, $pos );
        }
        $new_state{clues}->[$chosen_clue]->{cells} = [@$next_pair];

        push @dfs_stack, ( \%new_state );
    }
}


1;    # End of Games::ABC_Path::Generator

__END__

=pod

=encoding UTF-8

=head1 NAME

Games::ABC_Path::Generator - a generator for ABC Path puzzle games.

=head1 VERSION

version 0.6.0

=head1 SYNOPSIS

    use Games::ABC_Path::Generator;

    my $gen = Games::ABC_Path::Generator->new({seed => 1});

    # Returns a Games::ABC_Path::Generator::RiddleObj object.
    my $riddle = $gen->calc_riddle();

=head1 DESCRIPTION

ABC Path puzzle games are puzzle games where one is given a 5*5 grid which
should contain a consecutive path of the letters from 'A' to 'Y' (with vertical,
horizontal, diagonal, or anti-diagonal steps). The position of the letter 'A'
is given, and two letters are given for each of the columns, rows, main
diagonal and main anti-diagonal, which can appear anywhere there.

ABC Path can be played online at L<http://www.brainbashers.com/abcpath.asp> .

This package is a generator for ABC Path games, and it generates a different
layout with different clues for every random number generator seed.

=head1 SUBROUTINES/METHODS

=head2 my $gen = Games::ABC_Path::Generator->new({seed => $seed});

Initialised a new generator with the random number generator seed $seed .

=head2 $gen->calc_final_layout()

Calculates the final, solved, layout of the board based on the current
random seed.

Returns the layout as a L<Games::ABC_Path::Generator::FinalLayoutObj>
object.

=head2 $gen->calc_riddle()

Calculates the riddle (final state + initial hints) and returns it as an object.

=head1 AUTHOR

Shlomi Fish, L<http://www.shlomifish.org/> .

=head1 SEE ALSO

L<Games::ABC_Path::Solver> - a solver for ABC Path games which this
generator uses.

L<http://www.shlomifish.org/open-source/projects/japanese-puzzle-games/abc-path/> - the homepage of Shlomi Fish's ABC Path work.

L<http://www.brainbashers.com/abcpath.asp> - play ABC Path online on
brainbashers.com .

L<http://www.janko.at/> - Otto Janko, the creator of ABC Path.

=for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan

=head1 SUPPORT

=head2 Websites

The following websites have more information about this module, and may be of help to you. As always,
in addition to those websites please use your favorite search engine to discover more resources.

=over 4

=item *

MetaCPAN

A modern, open-source CPAN search engine, useful to view POD in HTML format.

L<https://metacpan.org/release/Games-ABC_Path-Generator>

=item *

RT: CPAN's Bug Tracker

The RT ( Request Tracker ) website is the default bug/issue tracking system for CPAN.

L<https://rt.cpan.org/Public/Dist/Display.html?Name=Games-ABC_Path-Generator>

=item *

CPANTS

The CPANTS is a website that analyzes the Kwalitee ( code metrics ) of a distribution.

L<http://cpants.cpanauthors.org/dist/Games-ABC_Path-Generator>

=item *

CPAN Testers

The CPAN Testers is a network of smoke testers who run automated tests on uploaded CPAN distributions.

L<http://www.cpantesters.org/distro/G/Games-ABC_Path-Generator>

=item *

CPAN Testers Matrix

The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.

L<http://matrix.cpantesters.org/?dist=Games-ABC_Path-Generator>

=item *

CPAN Testers Dependencies

The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.

L<http://deps.cpantesters.org/?module=Games::ABC_Path::Generator>

=back

=head2 Bugs / Feature Requests

Please report any bugs or feature requests by email to C<bug-games-abc_path-generator at rt.cpan.org>, or through
the web interface at L<https://rt.cpan.org/Public/Bug/Report.html?Queue=Games-ABC_Path-Generator>. You will be automatically notified of any
progress on the request by the system.

=head2 Source Code

The code is open to the world, and available for you to hack on. Please feel free to browse it and play
with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull
from your repository :)

L<https://github.com/shlomif/abc-path>

  git clone https://github.com/shlomif/abc-path

=head1 AUTHOR

Shlomi Fish <shlomif@cpan.org>

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website
L<https://github.com/shlomif/abc-path/issues>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2021 by Shlomi Fish.

This is free software, licensed under:

  The MIT (X11) License

=cut
