<?php

declare(strict_types=1);

namespace Psl\Type\Internal;

use Override;
use Psl\Type;
use Psl\Type\Exception\AssertException;
use Psl\Type\Exception\CoercionException;
use Stringable;

use function ctype_digit;
use function is_float;
use function is_int;
use function is_string;

/**
 * @extends Type\Type<float>
 *
 * @internal
 */
final readonly class FloatType extends Type\Type
{
    /**
     * @psalm-assert-if-true float $value
     */
    #[Override]
    public function matches(mixed $value): bool
    {
        return is_float($value);
    }

    /**
     * @throws CoercionException
     */
    #[Override]
    public function coerce(mixed $value): float
    {
        if (is_float($value)) {
            return $value;
        }

        if (is_int($value)) {
            return $value;
        }

        if (is_string($value) || $value instanceof Stringable) {
            $str = (string) $value;
            if ('' !== $str) {
                if (ctype_digit($str)) {
                    return (float) $str;
                }

                if (1 === preg_match("/^[+-]?(\d+([.]\d*)?([eE][+-]?\d+)?|[.]\d+([eE][+-]?\d+)?)$/", $str)) {
                    return (float) $str; // @mago-expect analysis:invalid-type-cast
                }
            }
        }

        throw CoercionException::withValue($value, $this->toString());
    }

    /**
     * @psalm-assert float $value
     *
     * @throws AssertException
     */
    #[Override]
    public function assert(mixed $value): float
    {
        if (is_float($value)) {
            return $value;
        }

        throw AssertException::withValue($value, $this->toString());
    }

    #[Override]
    public function toString(): string
    {
        return 'float';
    }
}
