<?php

require __DIR__ . '/../autoload.php';

use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;

const DICTIONARY = __DIR__ . '/../assets/words.txt';

echo "ANAGRAM FINDER\n";

$words = LazyCollection::make(function () {
    $fh = fopen(DICTIONARY, 'rb');
    try {
        while (($line = fgets($fh)) !== false) {
            yield rtrim($line, "\r\n");
        }
    } finally {
        fclose($fh);
    }
});

function output($message)
{
    $message = $message . PHP_EOL;
    print($message);
    flush();
//    ob_flush();
}


$anagramBase = readline("Enter the anagram: ");
echo "\n";
echo "Results for your anagram: " . $anagramBase . "\n";

$anagramChars = new Collection(explode($anagramBase, ""));
echo $words
    ->filter(fn (string $word) => ctype_alpha($word))
    ->filter(fn (string $word) => strtolower($word) === $word)
    ->map(fn (string $word) => new Collection(explode($word, "")))
    ->filter(fn (Collection $wordChars) => $wordChars->count() === $anagramChars->intersect($wordChars)->count())
->count();
//    ->map(fn (Collection $wordChars) => $wordChars->join(""))
//    ->each(fn (string $word) => output($word));
