% Find the Rail Cube canonical form used by railcube-enumeration.
%
%   scryer-prolog canonicalise.pl XIISSLIISSSOLLOSXISSILIISSOSSRROSRSR
%   scryer-prolog canonicalise.pl --all XIISSLIISSSOLLOSXISSILIISSOSSRROSRSR
%   ?- canonicalise('XIISSLIISSSOLLOSXISSILIISSOSSRROSRSR', Canonical).
%
% Compare rotations and reversed travel by the first loop's length.
% Break ties with the piece order S < L < R < I < O.
% The return to X must be positive. Keep mirror images separate.
% Check the geometry without fixing the inventory.
% --all lists each distinct cyclic start and each direction that preserves
% the inventory.
% The track logic uses ISO Prolog. Only the command-line adapter uses Scryer.
%
%    ^ ^
%  =(o.o)=
%    m m
% ~byakuren

:- set_prolog_flag(double_quotes, chars).

canonicalise(Input, Canonical) :-
    canonical_pieces(Input, Best),
    piece_chars(Best, Letters), atom_chars(Canonical, Letters).

equivalent_forms(Input, Forms) :-
    canonical_pieces(Input, Pieces),
    setof(Form, equivalent_form(Pieces, Form), Forms).

% Validate the track once. Use the same canonical form for both operations.
canonical_pieces(Input, Best) :-
    ( atom(Input) -> atom_chars(Input, Chars) ; Chars = Input ),
    read_pieces(Chars, Pieces),
    occurrences(x, Pieces, 2),
    setof(Key-Route, representative(Pieces, Key, Route), [_-Best|_]).

equivalent_form(Pieces, Form) :-
    direction(Pieces, Directed),
    rotation(Directed, Rotated),
    piece_chars(Rotated, Letters), atom_chars(Form, Letters).

% Each nonempty suffix gives one cyclic starting point.
rotation(Pieces, [P|Rest]) :-
    append_list(Before, [P|After], Pieces),
    append_list(After, Before, Rest).

% Backtracking finds the alternatives. setof/3 selects the smallest key.
representative(Pieces, key(Length, Order), [x|Rest]) :-
    direction(Pieces, Directed),
    rotation(Directed, [x|Rest]),
    valid_track([x|Rest]),
    append_list(First, [x|_], Rest),
    list_length(First, Length),
    piece_order(First, Order).

direction(Pieces, Pieces).
direction(Pieces, Reversed) :-
    % Reversing travel swaps L/R. Keep it only if it preserves the inventory.
    occurrences(l, Pieces, N), occurrences(r, Pieces, N),
    reverse_list(Pieces, Backwards),
    reverse_turns(Backwards, Reversed).

reverse_turns([], []).
reverse_turns([P|Ps], [Q|Qs]) :-
    ( P = l -> Q = r ; P = r -> Q = l ; Q = P ),
    reverse_turns(Ps, Qs).

% The first X fixes the position and rotation.
% The second X must have the same position and floor, with heading +Y.
% One of the two X starting points meets this condition.
valid_track([x|Pieces]) :-
    Start = pose([0,0,0], [0,0,-1], [1,0,0]),
    step(x, Start, Next, Material, Train),
    track(Pieces, Next, Material, Train, Start).

track([], End, _, _, End).
track([x|Pieces], pose([0,0,0], [0,0,-1], [0,1,0]), M, T, End) :-
    step(x, pose([0,0,0], [0,0,-1], [0,1,0]), Next, _, _),
    % The second pass uses the same physical X block.
    track(Pieces, Next, M, T, End).
track([P|Pieces], Pose, M, T, End) :-
    P \= x,
    step(P, Pose, Next, Material, Train),
    disjoint(Material, M), disjoint(Material, T), disjoint(Train, M),
    append_list(Material, M, Ms), append_list(Train, T, Ts),
    track(Pieces, Next, Ms, Ts, End).

% Each fact gives the exit pose, material cells and cells the train needs.
% These use the piece's local axes: +X forward, +Y left, +Z up.
piece(s, pose([1,0,0], [0,0,-1], [1,0,0]), [[0,0,0]], [[0,0,1]]).
piece(l, pose([1,2,0], [0,0,-1], [0,1,0]),
      [[0,0,0],[1,0,0],[0,1,0],[1,1,0]],
      [[0,0,1],[1,0,1],[0,1,1],[1,1,1]]).
piece(r, pose([1,-2,0], [0,0,-1], [0,-1,0]),
      [[0,0,0],[1,0,0],[0,-1,0],[1,-1,0]],
      [[0,0,1],[1,0,1],[0,-1,1],[1,-1,1]]).
piece(i, pose([1,0,2], [1,0,0], [0,0,1]),
      [[0,0,0],[1,0,0],[0,0,1],[1,0,1]], []).
piece(o, pose([0,0,-1], [-1,0,0], [0,0,-1]),
      [[0,0,0]], [[0,0,1],[1,0,1],[1,0,0]]).
piece(x, Pose, Material, Train) :- piece(s, Pose, Material, Train).

step(Piece, pose(Position, Floor, Heading), pose(End, NewFloor, NewHeading), M, T) :-
    piece(Piece, pose(Delta, LocalFloor, LocalHeading), Material, Train),
    negate(Floor, Up), cross(Up, Heading, Left),
    Frame = frame(Heading, Left, Up),
    transform(Frame, Delta, Displacement), add(Position, Displacement, End),
    transform(Frame, LocalFloor, NewFloor),
    transform(Frame, LocalHeading, NewHeading),
    cells(Material, Frame, Position, M), cells(Train, Frame, Position, T).

cells([], _, _, []).
cells([Local|Locals], Frame, Position, [World|Worlds]) :-
    transform(Frame, Local, Delta), add(Position, Delta, World),
    cells(Locals, Frame, Position, Worlds).

transform(frame([Dx,Dy,Dz],[Lx,Ly,Lz],[Ux,Uy,Uz]), [X,Y,Z], [A,B,C]) :-
    A is X*Dx + Y*Lx + Z*Ux,
    B is X*Dy + Y*Ly + Z*Uy,
    C is X*Dz + Y*Lz + Z*Uz.
add([A,B,C], [D,E,F], [X,Y,Z]) :- X is A+D, Y is B+E, Z is C+F.
negate([X,Y,Z], [A,B,C]) :- A is -X, B is -Y, C is -Z.
cross([A,B,C], [D,E,F], [X,Y,Z]) :- X is B*F-C*E, Y is C*D-A*F, Z is A*E-B*D.

% Use one table to print pieces and compare them in the database's order.
symbol(s, 'S', 0).
symbol(l, 'L', 1).
symbol(r, 'R', 2).
symbol(i, 'I', 3).
symbol(o, 'O', 4).
symbol(x, 'X', 5).

read_pieces([], []).
read_pieces([C|Cs], Pieces) :-
    char_code(C, Code),
    ( ( Code =:= 32 ; Code >= 9, Code =< 13 ) ->
        read_pieces(Cs, Pieces)
    ; ( Code >= 97, Code =< 122 -> Upper is Code-32 ; Upper = Code ),
      char_code(Letter, Upper), symbol(Piece, Letter, _),
      Pieces = [Piece|Rest], read_pieces(Cs, Rest)
    ).
piece_chars([], []).
piece_chars([P|Ps], [C|Cs]) :- symbol(P, C, _), piece_chars(Ps, Cs).
piece_order([], []).
piece_order([P|Ps], [N|Ns]) :- symbol(P, _, N), piece_order(Ps, Ns).

% These small list relations let the track code run without libraries.
append_list([], Ys, Ys).
append_list([X|Xs], Ys, [X|Zs]) :- append_list(Xs, Ys, Zs).
reverse_list(Xs, Ys) :- reverse_list(Xs, [], Ys).
reverse_list([], Ys, Ys).
reverse_list([X|Xs], Acc, Ys) :- reverse_list(Xs, [X|Acc], Ys).
list_length([], 0).
list_length([_|Xs], N) :- list_length(Xs, M), N is M+1.
occurrences(_, [], 0).
occurrences(P, [Q|Qs], N) :-
    occurrences(P, Qs, M), ( P = Q -> N is M+1 ; N = M ).
member_of(X, [X|_]).
member_of(X, [_|Xs]) :- member_of(X, Xs).
disjoint(Xs, Ys) :- \+ ( member_of(X, Xs), member_of(X, Ys) ).

% The Scryer adapter accepts FILE [--all] TRACK and an optional -- separator.
% Without a track argument, use the two relations at the Prolog prompt.
:- use_module(library(os), [argv/1, raw_argv/1]).
:- initialization(main).

main :-
    ( command_input(Mode, Chars) ->
        ( command_result(Mode, Chars) -> nl, halt
        ; write(user_error, 'Invalid track: expected a closed, collision-free circuit with two X traversals.'),
          nl(user_error), halt(1)
        )
    ; true
    ).

command_result(single, Chars) :- canonicalise(Chars, Canonical), write(Canonical).
command_result(all, Chars) :- equivalent_forms(Chars, Forms), writeq(Forms).

command_input(Mode, Chars) :-
    command_arguments(Args), track_argument(Args, Mode, Chars).
command_arguments(Args) :- argv(Args), Args \= [].
command_arguments(Args) :-
    raw_argv(Raw), append_list(_, [File|Args], Raw),
    append_list(_, ".pl", File).

track_argument([Chars], single, Chars).
track_argument(["--all", Chars], all, Chars).
track_argument([Chars, "--all"], all, Chars).
