import type {IsEqual} from '../is-equal.d.ts';
import type {IsStringLiteral} from '../is-string-literal.d.ts';
import type {_SplitOnDelimiter} from '../split.d.ts';
import type {CollapseLiterals} from '../collapse-literals.d.ts';
import type {AsciiPunctuationCharacter} from '../ascii-punctuation-character.d.ts';
import type {UnwrapBrandedPrimitive} from '../unwrap-branded-primitive.d.ts';

/**
Convert a string or number key to its template literal representation.

Note: This type is not the return type of the `.toString()` function.

Keep this separate from the public `ToString`: internal key and path matching relies on preserving branded template literal patterns and `${any}`.
*/
export type KeyToString<Key> = Key extends string | number ? `${Key}` : never;

/**
The types that `Array#join()` can stringify, and which `Join` accepts.

The builtin `join` method supports all these natively in the same way that typescript handles them so we can safely accept all of them.
*/
export type JoinableItem = string | number | bigint | boolean | undefined | null;

/**
Returns `Value` when it is a string literal that is equal to `CasedValue`, the result of a case transform on it, and `never` otherwise.

The value must not be empty, and it must not hold ASCII punctuation other than `AllowedPunctuation`, even punctuation that the transform keeps, like the dot in `'foo.bar'`.

@example
```
type A = CasedString<'foo-bar', 'foo-bar', '-'>; //=> 'foo-bar'
type B = CasedString<'fooBar', 'foo-bar', '-'>; //=> never
type C = CasedString<'foo.bar', 'foo.bar', '-'>; //=> never
type D = CasedString<string, string, '-'>; //=> never
```
*/
export type CasedString<
	Value extends string,
	CasedValue extends string,
	AllowedPunctuation extends string,
> = IsStringLiteral<Value> extends true
	// `Exclude` distributes over the members of a union, so one member that is empty or holds a foreign character removes itself and the whole union is rejected. A branded member is matched too, because the brand does not stop it from extending the pattern.
	? [Value] extends [Exclude<Value, '' | `${string}${Exclude<AsciiPunctuationCharacter, AllowedPunctuation>}${string}`>]
		// The value is turned into a plain string, because a string enum member is not equal to the string that the transform returns.
		// Unwrap unconditionally after the predicate so branded generics retain their primitive constraint.
		? IsEqual<`${UnwrapBrandedPrimitive<Value>}`, CasedValue> extends true
			? Value
			: never
		: never
	: never;

/**
Returns a boolean for whether `A` represents a number greater than `B`, where `A` and `B` are both numeric strings and have the same length.

@example
```
type A = SameLengthPositiveNumericStringGt<'50', '10'>;
//=> true

type B = SameLengthPositiveNumericStringGt<'10', '10'>;
//=> false
```
*/
type SameLengthPositiveNumericStringGt<A extends string, B extends string> = A extends `${infer FirstA}${infer RestA}`
	? B extends `${infer FirstB}${infer RestB}`
		? FirstA extends FirstB
			? SameLengthPositiveNumericStringGt<RestA, RestB>
			: PositiveNumericCharacterGt<FirstA, FirstB>
		: never
	: false;

type NumericString = '0123456789';

/**
Returns a boolean for whether `A` is greater than `B`, where `A` and `B` are both positive numeric strings.

TypeScript prints numbers of `1e21` and above, and positive numbers below `1e-6`, in exponential notation. Such a number is larger or smaller than any number in plain decimal notation, so a comparison with one exponential side is still decided. Returns `boolean` when both strings use exponential notation with an exponent of the same sign, because comparing digit by digit only works for plain decimal notation.

@example
```
type A = PositiveNumericStringGt<'500', '1'>;
//=> true

type B = PositiveNumericStringGt<'1', '1'>;
//=> false

type C = PositiveNumericStringGt<'1', '500'>;
//=> false

type D = PositiveNumericStringGt<'1.1', '1.05'>;
//=> true

type E = PositiveNumericStringGt<'1e+21', '1'>;
//=> true

type F = PositiveNumericStringGt<'1e-7', '0'>;
//=> true

type G = PositiveNumericStringGt<'2e+21', '1e+21'>;
//=> boolean
```
*/
export type PositiveNumericStringGt<A extends string, B extends string> = B extends unknown // Distribute before equality so one equal member cannot hide a smaller alternative.
	? A extends B
		? false
		// A positive exponent, like `1e+21`, is larger than any plain decimal number.
		: A extends `${string}e+${string}`
			? B extends `${string}e+${string}`
				? boolean
				: true
			: B extends `${string}e+${string}`
				? false
				// A negative exponent, like `1e-7`, is smaller than any plain decimal number except `0`.
				: A extends `${string}e-${string}`
					? B extends `${string}e-${string}`
						? boolean
						: B extends '0'
							? true
							: false
					: B extends `${string}e-${string}`
						? A extends '0'
							? false
							: true
						// Keep equality separate so generic integer comparisons retain their boolean constraint.
						: PositiveIntegerStringGt<IntegerPartOfNumericString<A>, IntegerPartOfNumericString<B>> extends infer IntegerResult extends boolean
							? IntegerResult extends true
								? true
								: IsEqual<IntegerPartOfNumericString<A>, IntegerPartOfNumericString<B>> extends true
									? FractionalPartGt<FractionalPartOfNumericString<A>, FractionalPartOfNumericString<B>>
									: false
							: never // Should never happen
	: never; // An empty right-hand union has no comparisons.

type IntegerPartOfNumericString<S extends string> = S extends `${infer IntegerPart}.${string}` ? IntegerPart : S;

type FractionalPartOfNumericString<S extends string> = S extends `${string}.${infer FractionalPart}` ? FractionalPart : '';

/**
Returns a boolean for whether `A` is greater than `B`, where `A` and `B` are both plain positive integer strings.

@example
```
type A = PositiveIntegerStringGt<'500', '1'>;
//=> true

type B = PositiveIntegerStringGt<'1', '1'>;
//=> false

type C = PositiveIntegerStringGt<'1', '500'>;
//=> false
```
*/
type PositiveIntegerStringGt<A extends string, B extends string> = CompareStringLength<A, B> extends infer LengthResult extends boolean | 'equal'
	? LengthResult extends 'equal' ? SameLengthPositiveNumericStringGt<A, B> : LengthResult
	: never;

// Walk both strings together until one ends, without building counting tuples.
type CompareStringLength<Left extends string, Right extends string> = Left extends `${string}${infer LeftRest}`
	? Right extends `${string}${infer RightRest}`
		? CompareStringLength<LeftRest, RightRest>
		: true
	: Right extends '' ? 'equal' : false;

/**
Returns a boolean for whether the fractional part `A` is greater than `B`. The first differing character decides, and a part that runs out of characters first is the smaller one, so `'5'` is less than `'50'` while `'50'` is greater than `'5'`. TypeScript never prints a numeric literal with a trailing zero, so the two are the same value in practice and the difference cannot be reached.
*/
type FractionalPartGt<A extends string, B extends string> = A extends B
	? false
	: B extends ''
		? true
		: A extends ''
			? false
			: A extends `${infer FirstA}${infer RestA}`
				? B extends `${infer FirstB}${infer RestB}`
					? FirstA extends FirstB
						? FractionalPartGt<RestA, RestB>
						: PositiveNumericCharacterGt<FirstA, FirstB>
					: never // Should never happen
				: never; // Should never happen

/**
Returns a boolean for whether `A` represents a number greater than `B`, where `A` and `B` are both positive numeric characters.

@example
```
type A = PositiveNumericCharacterGt<'5', '1'>;
//=> true

type B = PositiveNumericCharacterGt<'1', '1'>;
//=> false
```
*/
// Each digit occurs once in ascending order, so B must appear before A.
type PositiveNumericCharacterGt<A extends string, B extends string> = NumericString extends `${string}${B}${string}${A}${string}` ? true : false;

/**
Split a property path into a tuple of string keys, including numeric indices as strings. Handles dot and square-bracket notation.

@example
```
type A = ParsePathToStringSegments<'foo.bar.baz'>;
//=> ['foo', 'bar', 'baz']

type B = ParsePathToStringSegments<'foo[0].bar.baz'>;
//=> ['foo', '0', 'bar', 'baz']
```
*/
// Path parsing always uses a dot and permits non-literal input, so it can reuse the split loop after bracket normalization.
// Keep this separate from `ParsePath`: `Get` reads string keys directly, so converting indices to numbers would add work only to convert them back to strings.
export type ParsePathToStringSegments<Path extends string> = _SplitOnDelimiter<FixPathSquareBrackets<Path>, '.'>;

/**
Remove brands from property paths while preserving empty intersections used by `LiteralUnion`.

Distribute before normalization so a wide path cannot erase another member's known segments.

@example
```
type Path = UnwrapPathBrand<'users.name' & {readonly brand: unique symbol}>;
//=> 'users.name'
```
*/
export type UnwrapPathBrand<Path> = Path extends unknown
	? Exclude<keyof CollapseLiterals<Path>, keyof string | keyof number> extends never ? Path : UnwrapBrandedPrimitive<Path>
	: never;

/**
Replaces square-bracketed dot notation with dots, for example, `foo[0].bar` -> `foo.0.bar`.
*/
// The fixed part of the path is kept in `Result`, so the recursion is in tail position and a long path does not hit the recursion limit.
type FixPathSquareBrackets<Path extends string, Result extends string = ''> =
	Path extends `[${infer Head}]${infer Tail}`
		? Tail extends `[${string}`
			? FixPathSquareBrackets<Tail, `${Result}${Head}.`>
			: FixPathSquareBrackets<Tail, `${Result}${Head}`>
		: Path extends `${infer Head}[${infer Middle}]${infer Tail}`
			? FixPathSquareBrackets<`[${Middle}]${Tail}`, `${Result}${Head}.`>
			: `${Result}${Path}`;

export {};
