import type {_SplitOnRestElement, SplitOnRestElement} from './split-on-rest-element.d.ts';
import type {IsReadonlyArray} from './is-readonly-array.d.ts';
import type {UnknownArray} from './unknown-array.d.ts';
import type {IfNotAnyOrNever} from './internal/type.d.ts';
import type {ExtractRestElement} from './extract-rest-element.d.ts'; // For `@link`

/**
Create a tuple with the [`rest`](https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types) element removed.

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

type T1 = ExcludeRestElement<[number, ...string[], string, 'foo']>;
//=> [number, string, 'foo']

type T2 = ExcludeRestElement<[...boolean[], string]>;
//=> [string]

type T3 = ExcludeRestElement<[...Array<'foo'>, true]>;
//=> [true]

type T4 = ExcludeRestElement<[number, string]>;
//=> [number, string]
```

@see {@link ExtractRestElement}
@see {@link SplitOnRestElement}
@category Array
*/
export type ExcludeRestElement<Array_ extends UnknownArray> = IfNotAnyOrNever<Array_, {
	// The union is distributed, so that `readonly` is decided per member. Without it, `IsReadonlyArray` resolves to `boolean` for a mixed union and every member loses it.
	ifNot: Array_ extends unknown
		// The public splitter would repeat the input guards, distribution and readonly restoration already handled here.
		? (
			// A fixed-length copy has no rest to remove; copying first keeps array length refinements on the splitter path.
			number extends [...Array_]['length']
				? _SplitOnRestElement<Array_, {preserveOptionalModifier: true}>
				: [Array_, [], []]
		) extends infer Result
			? Result extends readonly UnknownArray[]
				? IsReadonlyArray<Array_> extends true
					? Readonly<[...Result[0], ...Result[2]]>
					: [...Result[0], ...Result[2]]
				: never
			: never
		: never;
}>;

export {};
