<?php

declare(strict_types=1);

namespace Psl\Iter;

use Closure;
use Countable;
use Generator;
use SeekableIterator;

use function array_key_exists;

/**
 * @template   Tk
 * @template   Tv
 *
 * @implements SeekableIterator<Tk, Tv>
 */
final class Iterator implements Countable, SeekableIterator
{
    /**
     * @var null|Generator<Tk, Tv, mixed, mixed>
     */
    private null|Generator $generator;

    /**
     * @var array<int, array{0: Tk, 1: Tv}>
     */
    private array $entries = [];

    /**
     *  Whether the current value/key pair has been added to the local entries.
     */
    private bool $saved = true;

    /**
     * Current cursor position for the local entries.
     */
    private int $position = 0;

    /**
     * The size of the generator.
     *
     * @var null|int<0, max>
     */
    private null|int $count = null;

    /**
     * @param Generator<Tk, Tv, mixed, mixed> $generator
     */
    public function __construct(Generator $generator)
    {
        $this->generator = $generator;
    }

    /**
     * Create an iterator from a factory.
     *
     * @template Tsk
     * @template Tsv
     *
     * @param (Closure(): iterable<Tsk, Tsv>) $factory
     *
     * @return Iterator<Tsk, Tsv>
     */
    public static function from(Closure $factory): Iterator
    {
        return self::create($factory());
    }

    /**
     * Create an iterator from an iterable.
     *
     * @template Tsk
     * @template Tsv
     *
     * @param iterable<Tsk, Tsv> $iterable
     *
     * @return Iterator<Tsk, Tsv>
     */
    public static function create(iterable $iterable): Iterator
    {
        if ($iterable instanceof Generator) {
            return new self($iterable);
        }

        $factory =
            /**
             * @return Generator<Tsk, Tsv, mixed, mixed>
             */
            static fn(): Generator => yield from $iterable;

        return new self($factory());
    }

    /**
     * Return the current element.
     *
     * @return Tv
     */
    #[\Override]
    public function current(): mixed
    {
        $this->save();

        return $this->entries[$this->position][1];
    }

    /**
     * Checks if current position is valid.
     */
    #[\Override]
    public function valid(): bool
    {
        if (array_key_exists($this->position, $this->entries)) {
            return true;
        }

        if (null !== $this->generator && $this->generator->valid()) {
            return true;
        }

        $this->generator = null;
        return false;
    }

    private function save(): void
    {
        if ($this->generator) {
            if ([] === $this->entries) {
                $this->saved = false;
            }

            if (!$this->saved && $this->generator->valid()) {
                $this->saved = true;
                $this->entries[] = [$this->generator->key(), $this->generator->current()];
            }
        }
    }

    /**
     * Return the key of the current element.
     *
     * @return Tk
     */
    #[\Override]
    public function key(): mixed
    {
        $this->save();

        return $this->entries[$this->position][0];
    }

    /**
     * Rewind the Iterator to the first element.
     */
    #[\Override]
    public function rewind(): void
    {
        $this->position = 0;
    }

    /**
     * Seek to the given position.
     *
     * @param int<0, max> $offset
     *
     * @throws Exception\OutOfBoundsException If $offset is out-of-bounds.
     */
    #[\Override]
    public function seek(int $offset): void
    {
        if ($offset <= $this->position) {
            $this->position = $offset;
            return;
        }

        if ($this->generator) {
            do {
                $this->save();
                $this->next();
                if (!$this->generator->valid()) {
                    $this->generator = null;
                    throw new Exception\OutOfBoundsException('Position is out-of-bounds.');
                }
            } while ($this->position < $offset);

            return;
        }

        if ($offset >= $this->count()) {
            throw new Exception\OutOfBoundsException('Position is out-of-bounds.');
        }

        $this->position = $offset;
    }

    /**
     * Move forward to the next element.
     */
    #[\Override]
    public function next(): void
    {
        $this->position++;

        if (
            array_key_exists($this->position, $this->entries)
            || null === $this->generator
            || !$this->generator->valid()
        ) {
            return;
        }

        $this->generator->next();
        $this->saved = false;
    }

    /**
     * @return int<0, max>
     */
    #[\Override]
    public function count(): int
    {
        if ($this->generator) {
            $previous = $this->position;
            do {
                $this->save();
                $this->next();
            } while ($this->generator->valid());

            $this->position = $previous;

            $this->generator = null;
        }

        if (null !== $this->count) {
            return $this->count;
        }

        /** @var int<0, max> */
        $this->count = count($this->entries);

        return $this->count;
    }
}
