import type {UnwrapBrandedPrimitive} from './unwrap-branded-primitive.d.ts';
import type {IsNumericLiteral} from './is-numeric-literal.d.ts';
import type {IsNegative, PositiveInfinity} from './numeric.d.ts';
import type {DigitCharacter} from './characters.d.ts';

/**
Returns a new string which contains the specified number of copies of a given string, just like `String#repeat()`.

@example
```
import type {StringRepeat} from 'type-fest';

declare function stringRepeat<
	S extends string,
	Count extends number,
>(input: S, count: Count): StringRepeat<S, Count>;

// The return type is the exact string literal, not just `string`.

stringRepeat('foo', 2);
//=> 'foofoo'

stringRepeat('=', 3);
//=> '==='
```

Note: If the specified count has a decimal part, the decimal part will be ignored.

@example
```
import type {StringRepeat} from 'type-fest';

type DecimalCount = StringRepeat<'foo', 2.5>;
//=> 'foofoo'
```

@category String
@category Template literal
*/
export type StringRepeat<S extends string, Count extends number> = _StringRepeat<S extends object ? UnwrapBrandedPrimitive<S> : S, Count extends object ? UnwrapBrandedPrimitive<Count> : Count>;

// Brands describe the original values, so all count checks and interpolation operate on unwrapped primitives.
type _StringRepeat<S extends string, Count extends number> =
	Count extends unknown // To distribute `Count`
		// `String#repeat()` truncates the count toward zero, so counts between -1 and 1 produce an empty string. TypeScript prints magnitudes below `1e-6` in scientific notation, which must be handled before the fallback for large counts.
		? `${Count}` extends `-0.${string}` | `${string}e-${string}`
			? ''
			// An infinite count throws before the empty input shortcut.
			: Count extends PositiveInfinity
				? never
				: IsNegative<Count> extends true
					? never
					: S extends ''
						? ''
						: IsNumericLiteral<Count> extends false
							? string
							: `${Count}` extends `${string}e${string}`
								? string
								: BuildStringDigitByDigit<S, `${Count}`>
		: never;

type BuildStringDigitByDigit<S extends string, Count extends string, Accumulator extends string = ''> =
	Count extends `${infer First extends DigitCharacter}${infer Rest}`
		? BuildStringDigitByDigit<
			S,
			Rest,
			`${RepeatStringTenTimes<Accumulator>}${DigitStringRepeat<S, First>}`
		>
		: Accumulator;

type RepeatStringTenTimes<S extends string> = `${S}${S}${S}${S}${S}${S}${S}${S}${S}${S}`;

// String-keyed lookup avoids building tuple machinery for the digit table.
type DigitStringRepeat<S extends string, Digit extends DigitCharacter> = {
	'0': '';
	'1': `${S}`;
	'2': `${S}${S}`;
	'3': `${S}${S}${S}`;
	'4': `${S}${S}${S}${S}`;
	'5': `${S}${S}${S}${S}${S}`;
	'6': `${S}${S}${S}${S}${S}${S}`;
	'7': `${S}${S}${S}${S}${S}${S}${S}`;
	'8': `${S}${S}${S}${S}${S}${S}${S}${S}`;
	'9': `${S}${S}${S}${S}${S}${S}${S}${S}${S}`;
}[Digit];

export {};
