Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

66.5 KB
Raw Blame
import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
/**
 * Auto-generated from the Django backend OpenAPI schema.
 * To modify these types, update the Django serializers or views, then run:
 *   hogli build:openapi
 * Questions or issues? #team-devex on Slack
 *
 * PostHog API - generated
 * OpenAPI spec version: 1.0.0
 */
import type {
    ActivityLogPaginatedResponseApi,
    ArchiveExperimentApi,
    BulkUpdateTagsRequestApi,
    BulkUpdateTagsResponseApi,
    CopyExperimentToProjectApi,
    CreateFromPromptInputApi,
    EndExperimentApi,
    ExperimentApi,
    ExperimentFlagCleanupTargetApi,
    ExperimentFlagCleanupTaskApi,
    ExperimentHealthApi,
    ExperimentHealthInputsApi,
    ExperimentHoldoutApi,
    ExperimentHoldoutsListParams,
    ExperimentInSessionExposureApi,
    ExperimentMatchingIdsResponseApi,
    ExperimentMetricsRecalculationJobApi,
    ExperimentMetricsRecalculationLatestApi,
    ExperimentMetricsRecalculationRunApi,
    ExperimentSavedMetricApi,
    ExperimentSavedMetricsListParams,
    ExperimentSessionBucketRequestApi,
    ExperimentSessionBucketResponseApi,
    ExperimentSessionContextResponseApi,
    ExperimentSessionContextsRequestApi,
    ExperimentSessionContextsResponseApi,
    ExperimentSessionEventDeltaResponseApi,
    ExperimentSetupContextInputApi,
    ExperimentSetupContextResponseApi,
    ExperimentWriteApi,
    ExperimentsActivityRetrieveParams,
    ExperimentsListParams,
    ExperimentsMatchingIdsRetrieveParams,
    ExperimentsPromptTemplatesRetrieve200Item,
    ExperimentsRunningTimeTargetRetrieveParams,
    ExperimentsSessionContextRetrieveParams,
    ExperimentsTimeseriesResultsRetrieveParams,
    PaginatedExperimentBasicListApi,
    PaginatedExperimentHoldoutListApi,
    PaginatedExperimentSavedMetricListApi,
    PatchedExperimentHoldoutApi,
    PatchedExperimentSavedMetricApi,
    PatchedExperimentWriteApi,
    RecalculateMetricsRequestApi,
    RunningTimeCalculationInputApi,
    RunningTimeCalculationResultApi,
    RunningTimeTargetApi,
    ShipVariantApi,
} from './api.schemas'

// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B

type WritableKeys<T> = {
    [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
}[keyof T]

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never

type Writable<T> = Pick<T, WritableKeys<T>>
type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
    ? {
          [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
      }
    : DistributeReadOnlyOverUnions<T>

export const getExperimentHoldoutsListUrl = (projectId: string, params?: ExperimentHoldoutsListParams) => {
    const normalizedParams = new URLSearchParams()

    Object.entries(params || {}).forEach(([key, value]) => {
        if (value !== undefined) {
            normalizedParams.append(key, value === null ? 'null' : String(value))
        }
    })

    const stringifiedParams = normalizedParams.toString()

    return stringifiedParams.length > 0
        ? `/api/projects/${projectId}/experiment_holdouts/?${stringifiedParams}`
        : `/api/projects/${projectId}/experiment_holdouts/`
}

/**
 * Create, read, update and delete experiment holdouts.
 */
export const experimentHoldoutsList = async (
    projectId: string,
    params?: ExperimentHoldoutsListParams,
    options?: RequestInit
): Promise<PaginatedExperimentHoldoutListApi> => {
    return apiMutator<PaginatedExperimentHoldoutListApi>(getExperimentHoldoutsListUrl(projectId, params), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentHoldoutsCreateUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiment_holdouts/`
}

/**
 * Create, read, update and delete experiment holdouts.
 */
export const experimentHoldoutsCreate = async (
    projectId: string,
    experimentHoldoutApi: NonReadonly<ExperimentHoldoutApi>,
    options?: RequestInit
): Promise<ExperimentHoldoutApi> => {
    return apiMutator<ExperimentHoldoutApi>(getExperimentHoldoutsCreateUrl(projectId), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentHoldoutApi),
    })
}

export const getExperimentHoldoutsRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiment_holdouts/${id}/`
}

/**
 * Create, read, update and delete experiment holdouts.
 */
export const experimentHoldoutsRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentHoldoutApi> => {
    return apiMutator<ExperimentHoldoutApi>(getExperimentHoldoutsRetrieveUrl(projectId, id), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentHoldoutsUpdateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiment_holdouts/${id}/`
}

/**
 * Create, read, update and delete experiment holdouts.
 */
export const experimentHoldoutsUpdate = async (
    projectId: string,
    id: number,
    experimentHoldoutApi: NonReadonly<ExperimentHoldoutApi>,
    options?: RequestInit
): Promise<ExperimentHoldoutApi> => {
    return apiMutator<ExperimentHoldoutApi>(getExperimentHoldoutsUpdateUrl(projectId, id), {
        ...options,
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentHoldoutApi),
    })
}

export const getExperimentHoldoutsPartialUpdateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiment_holdouts/${id}/`
}

/**
 * Create, read, update and delete experiment holdouts.
 */
export const experimentHoldoutsPartialUpdate = async (
    projectId: string,
    id: number,
    patchedExperimentHoldoutApi?: NonReadonly<PatchedExperimentHoldoutApi>,
    options?: RequestInit
): Promise<ExperimentHoldoutApi> => {
    return apiMutator<ExperimentHoldoutApi>(getExperimentHoldoutsPartialUpdateUrl(projectId, id), {
        ...options,
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(patchedExperimentHoldoutApi),
    })
}

export const getExperimentHoldoutsDestroyUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiment_holdouts/${id}/`
}

/**
 * Create, read, update and delete experiment holdouts.
 */
export const experimentHoldoutsDestroy = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<void> => {
    return apiMutator<void>(getExperimentHoldoutsDestroyUrl(projectId, id), {
        ...options,
        method: 'DELETE',
    })
}

export const getExperimentSavedMetricsListUrl = (projectId: string, params?: ExperimentSavedMetricsListParams) => {
    const normalizedParams = new URLSearchParams()

    Object.entries(params || {}).forEach(([key, value]) => {
        if (value !== undefined) {
            normalizedParams.append(key, value === null ? 'null' : String(value))
        }
    })

    const stringifiedParams = normalizedParams.toString()

    return stringifiedParams.length > 0
        ? `/api/projects/${projectId}/experiment_saved_metrics/?${stringifiedParams}`
        : `/api/projects/${projectId}/experiment_saved_metrics/`
}

export const experimentSavedMetricsList = async (
    projectId: string,
    params?: ExperimentSavedMetricsListParams,
    options?: RequestInit
): Promise<PaginatedExperimentSavedMetricListApi> => {
    return apiMutator<PaginatedExperimentSavedMetricListApi>(getExperimentSavedMetricsListUrl(projectId, params), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentSavedMetricsCreateUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiment_saved_metrics/`
}

export const experimentSavedMetricsCreate = async (
    projectId: string,
    experimentSavedMetricApi: NonReadonly<ExperimentSavedMetricApi>,
    options?: RequestInit
): Promise<ExperimentSavedMetricApi> => {
    return apiMutator<ExperimentSavedMetricApi>(getExperimentSavedMetricsCreateUrl(projectId), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentSavedMetricApi),
    })
}

export const getExperimentSavedMetricsRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiment_saved_metrics/${id}/`
}

export const experimentSavedMetricsRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentSavedMetricApi> => {
    return apiMutator<ExperimentSavedMetricApi>(getExperimentSavedMetricsRetrieveUrl(projectId, id), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentSavedMetricsUpdateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiment_saved_metrics/${id}/`
}

export const experimentSavedMetricsUpdate = async (
    projectId: string,
    id: number,
    experimentSavedMetricApi: NonReadonly<ExperimentSavedMetricApi>,
    options?: RequestInit
): Promise<ExperimentSavedMetricApi> => {
    return apiMutator<ExperimentSavedMetricApi>(getExperimentSavedMetricsUpdateUrl(projectId, id), {
        ...options,
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentSavedMetricApi),
    })
}

export const getExperimentSavedMetricsPartialUpdateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiment_saved_metrics/${id}/`
}

export const experimentSavedMetricsPartialUpdate = async (
    projectId: string,
    id: number,
    patchedExperimentSavedMetricApi?: NonReadonly<PatchedExperimentSavedMetricApi>,
    options?: RequestInit
): Promise<ExperimentSavedMetricApi> => {
    return apiMutator<ExperimentSavedMetricApi>(getExperimentSavedMetricsPartialUpdateUrl(projectId, id), {
        ...options,
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(patchedExperimentSavedMetricApi),
    })
}

export const getExperimentSavedMetricsDestroyUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiment_saved_metrics/${id}/`
}

export const experimentSavedMetricsDestroy = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<void> => {
    return apiMutator<void>(getExperimentSavedMetricsDestroyUrl(projectId, id), {
        ...options,
        method: 'DELETE',
    })
}

export const getExperimentsListUrl = (projectId: string, params?: ExperimentsListParams) => {
    const normalizedParams = new URLSearchParams()

    Object.entries(params || {}).forEach(([key, value]) => {
        if (value !== undefined) {
            normalizedParams.append(key, value === null ? 'null' : String(value))
        }
    })

    const stringifiedParams = normalizedParams.toString()

    return stringifiedParams.length > 0
        ? `/api/projects/${projectId}/experiments/?${stringifiedParams}`
        : `/api/projects/${projectId}/experiments/`
}

/**
 * List experiments for the current project. Supports filtering by status and archival state.
 */
export const experimentsList = async (
    projectId: string,
    params?: ExperimentsListParams,
    options?: RequestInit
): Promise<PaginatedExperimentBasicListApi> => {
    return apiMutator<PaginatedExperimentBasicListApi>(getExperimentsListUrl(projectId, params), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsCreateUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiments/`
}

/**
 * Create a new experiment in draft status with optional metrics.
 */
export const experimentsCreate = async (
    projectId: string,
    experimentWriteApi: NonReadonly<ExperimentWriteApi>,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsCreateUrl(projectId), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentWriteApi),
    })
}

export const getExperimentsRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/`
}

/**
 * Retrieve a single experiment by ID, including its current status, metrics, feature flag, and results metadata.
 */
export const experimentsRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsRetrieveUrl(projectId, id), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsUpdateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/`
}

/**
 * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
 *
 * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
 * decorator on serializer methods and converts them into the same responses the viewset path
 * produces (see decorators._result_to_response), so both paths share one contract.
 */
export const experimentsUpdate = async (
    projectId: string,
    id: number,
    experimentWriteApi: NonReadonly<ExperimentWriteApi>,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsUpdateUrl(projectId, id), {
        ...options,
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentWriteApi),
    })
}

export const getExperimentsPartialUpdateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/`
}

/**
 * Update an experiment. Use this to modify experiment properties such as name, description, metrics, variants, and configuration. Metrics can be added, changed and removed at any time. Feature-flag config (variants, rollout, payloads) is sent via the feature_flag object.
 */
export const experimentsPartialUpdate = async (
    projectId: string,
    id: number,
    patchedExperimentWriteApi?: NonReadonly<PatchedExperimentWriteApi>,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsPartialUpdateUrl(projectId, id), {
        ...options,
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(patchedExperimentWriteApi),
    })
}

export const getExperimentsDestroyUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/`
}

/**
 * Hard delete of this model is not allowed. Use a patch API call to set "deleted" to true
 */
export const experimentsDestroy = async (projectId: string, id: number, options?: RequestInit): Promise<unknown> => {
    return apiMutator<unknown>(getExperimentsDestroyUrl(projectId, id), {
        ...options,
        method: 'DELETE',
    })
}

export const getExperimentsActivityRetrieveUrl = (
    projectId: string,
    id: number,
    params?: ExperimentsActivityRetrieveParams
) => {
    const normalizedParams = new URLSearchParams()

    Object.entries(params || {}).forEach(([key, value]) => {
        if (value !== undefined) {
            normalizedParams.append(key, value === null ? 'null' : String(value))
        }
    })

    const stringifiedParams = normalizedParams.toString()

    return stringifiedParams.length > 0
        ? `/api/projects/${projectId}/experiments/${id}/activity/?${stringifiedParams}`
        : `/api/projects/${projectId}/experiments/${id}/activity/`
}

/**
 * Change history for this experiment.
 *
 * Returns a paginated audit trail of changes to the experiment, its holdouts and
 * shared metrics, and its linked feature flag: who made each change, what changed
 * (field-level before/after values), and when. Ordered newest first.
 */
export const experimentsActivityRetrieve = async (
    projectId: string,
    id: number,
    params?: ExperimentsActivityRetrieveParams,
    options?: RequestInit
): Promise<ActivityLogPaginatedResponseApi> => {
    return apiMutator<ActivityLogPaginatedResponseApi>(getExperimentsActivityRetrieveUrl(projectId, id, params), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsArchiveCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/archive/`
}

/**
 * Archive an ended experiment.
 *
 * Hides the experiment from the default list view. The experiment can be
 * restored at any time by updating archived=false. When the linked feature
 * flag is still enabled, pass disable_feature_flag=true to also disable and
 * archive it. Returns 400 if the experiment is already archived or has not
 * ended yet.
 */
export const experimentsArchiveCreate = async (
    projectId: string,
    id: number,
    archiveExperimentApi?: ArchiveExperimentApi,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsArchiveCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(archiveExperimentApi),
    })
}

export const getExperimentsCopyToProjectCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/copy_to_project/`
}

/**
 * Copy an experiment into another project in the same organization as a new draft.
 */
export const experimentsCopyToProjectCreate = async (
    projectId: string,
    id: number,
    copyExperimentToProjectApi: CopyExperimentToProjectApi,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsCopyToProjectCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(copyExperimentToProjectApi),
    })
}

export const getExperimentsCreateExposureCohortForExperimentCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/create_exposure_cohort_for_experiment/`
}

/**
 * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
 *
 * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
 * decorator on serializer methods and converts them into the same responses the viewset path
 * produces (see decorators._result_to_response), so both paths share one contract.
 */
export const experimentsCreateExposureCohortForExperimentCreate = async (
    projectId: string,
    id: number,
    experimentApi: NonReadonly<ExperimentApi>,
    options?: RequestInit
): Promise<void> => {
    return apiMutator<void>(getExperimentsCreateExposureCohortForExperimentCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentApi),
    })
}

export const getExperimentsDuplicateCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/duplicate/`
}

/**
 * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
 *
 * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
 * decorator on serializer methods and converts them into the same responses the viewset path
 * produces (see decorators._result_to_response), so both paths share one contract.
 */
export const experimentsDuplicateCreate = async (
    projectId: string,
    id: number,
    experimentApi: NonReadonly<ExperimentApi>,
    options?: RequestInit
): Promise<void> => {
    return apiMutator<void>(getExperimentsDuplicateCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentApi),
    })
}

export const getExperimentsEndCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/end/`
}

/**
 * End a running experiment without shipping a variant.
 *
 * Sets end_date to now and marks the experiment as stopped. The feature
 * flag is NOT modified — users continue to see their assigned variants
 * and exposure events ($feature_flag_called) continue to be recorded.
 * However, only data up to end_date is included in experiment results.
 *
 * Use this when:
 *
 * - You want to freeze the results window without changing which variant
 *   users see.
 * - A variant was already shipped manually via the feature flag UI and
 *   the experiment just needs to be marked complete.
 *
 * The end_date can be adjusted after ending via PATCH if it needs to be
 * backdated (e.g. to match when the flag was actually paused).
 *
 * Other options:
 * - Use ship_variant to end the experiment AND roll out a single variant to 100%% of users.
 * - Use pause to deactivate the flag without ending the experiment (stops variant assignment but does not freeze results).
 *
 * Returns 400 if the experiment is not running.
 */
export const experimentsEndCreate = async (
    projectId: string,
    id: number,
    endExperimentApi?: EndExperimentApi,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsEndCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(endExperimentApi),
    })
}

export const getExperimentsFlagCleanupTargetRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/flag_cleanup_target/`
}

/**
 * Repository a flag-cleanup pull request for this experiment would be opened in.
 *
 * Resolution order: the experiment's saved repository, else the environment's default
 * cleanup repository, else the team's only connected GitHub repository. When the team
 * has several repositories and none is saved (source=ambiguous), pass one via
 * `repository` on end/ship_variant.
 */
export const experimentsFlagCleanupTargetRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentFlagCleanupTargetApi> => {
    return apiMutator<ExperimentFlagCleanupTargetApi>(getExperimentsFlagCleanupTargetRetrieveUrl(projectId, id), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsFlagCleanupTaskRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/flag_cleanup_task/`
}

/**
 * Status of the flag-cleanup Desktop task opened for this experiment.
 *
 * When an experiment was ended or shipped with open_cleanup_pr=true, a Desktop task
 * removes the experiment's feature-flag code and opens a draft pull request. This
 * returns that task's latest run status and the PR URL once one is opened. Poll
 * until is_terminal is true. Returns 404 when no cleanup task was opened.
 */
export const experimentsFlagCleanupTaskRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentFlagCleanupTaskApi> => {
    return apiMutator<ExperimentFlagCleanupTaskApi>(getExperimentsFlagCleanupTaskRetrieveUrl(projectId, id), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsFreezeExposureCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/freeze_exposure/`
}

/**
 * Freeze exposure on a running experiment while metrics keep flowing.
 *
 * Snapshots the already-exposed users into a static cohort and narrows the
 * linked feature flag so only those users keep matching — new users can no
 * longer enter the experiment. ``end_date`` is left null so long-term metrics
 * (revenue/LTV/renewals/retention) keep accumulating. Enrolled users keep
 * their assigned variant. The serialized status becomes 'exposure_frozen'.
 *
 * Returns 400 if the experiment is not running, exposure is already frozen,
 * the experiment is group-aggregated (group flags cannot be frozen with a
 * person cohort), or the exposed set is too large to snapshot synchronously.
 */
export const experimentsFreezeExposureCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsFreezeExposureCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
    })
}

export const getExperimentsHealthRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/health/`
}

/**
 * Health check findings for this experiment: problems in its configuration and its feature flag
 * that keep it from producing trustworthy results, each with a fix. `checks` gives the result of
 * each check, so a check that found no problem can be told from one that did not apply or could
 * not read an input.
 *
 * The checks here read the experiment, its flag, its linked metrics, the project's event and
 * property definitions, the cohorts of the exposure criteria, and the changes of the flag's
 * variant split since launch. The checks that read exposure counts come with the
 * exposure query. The split-change check compares the split changes with the exposures only
 * for exposure criteria that name an event without property filters. When the split changed
 * after launch and the criteria have filters or an action, or an API key lacks `query:read`,
 * it returns an info finding with the subcode `not_checked` and the cause in
 * `reason`. A caller who can't view the linked flag's history (viewer access to the
 * flag and, with an API key, `activity_log:read`) gets that finding for every running
 * experiment, because the changes are not read.
 *
 * Two checks read whether the project received an event from its event definitions: a
 * definition without `last_seen_at`, such as one Wizard wrote for a planned event, counts as
 * not received. A name whose definition was deleted since launch, or in the last day for a
 * draft, is not checked, because ingestion writes the definition again only when the event
 * arrives. No missing definition is checked when ingestion saw none of the experiment's events
 * in the last day, because ingestion can be set to skip a team. `metric_event_not_ingested`
 * names each metric that
 * reads an event the project never received, in the `evidence` keys `metric_N`,
 * `metric_N_role` and `metric_N_events`. `exposure_criteria_cannot_match` reports a custom
 * exposure event the project never received (`exposure_event_not_ingested`), a
 * `$feature_flag` filter on the flag call events that requires another flag
 * (`filter_on_another_flag`), and a filter on an event or person property that the project has
 * no definition of, with an operator that a missing property fails
 * (`filter_on_property_not_ingested`, the keys in `evidence.properties`). A property whose
 * definition was ever deleted is not checked, and neither is an event property filter on an
 * action or on `$groupidentify`, whose properties ingestion keeps no definitions of. An event
 * or property not received is info before launch, in the first 24 hours after launch, and when
 * only secondary metrics read it, and a warning otherwise. `filter_on_another_flag` is a
 * warning in every state, `filter_on_property_not_ingested` also reports after the end, and
 * the other findings stop at the end.
 *
 * `exposure_filters` reads the cohort filters of the exposure criteria and of the activation,
 * not the test account filters. `exposure_filter_on_dynamic_cohort` is a warning in every
 * state: the results use the members of a dynamic cohort at the calculation, not at exposure.
 * Its subcode is `cohort_forces_variant` when a release condition of the flag that matches the
 * cohort's members gives one variant, `cohort_in_release_conditions` when the release
 * conditions match its members otherwise, and `evidence.cohort_ids` names the cohorts. Both
 * subcodes need the exposure criteria to keep the members too, not to leave them out.
 *
 * `metric_cannot_compile` builds and compiles the query of each metric without running it, as
 * the caller, so a metric that every calculation fails on shows before launch. A metric that
 * reads a warehouse table or view the caller may not query is not checked for them. The finding
 * names each failing metric in the `evidence` keys `metric_N`, `metric_N_role`, `metric_N_error`
 * (the error class, which is also the subcode of the first metric) and `metric_N_message` (the
 * compiler's message). It is a warning when a primary metric fails, also after the end, because
 * the calculation after the fix reads the events up to the end. It is info otherwise. A failure
 * inside ClickHouse, such as a type that the data holds, isn't found. A failing metric compiles
 * again on every request. A metric that compiles is cached per caller for a day, so a cohort or
 * table that is deleted after a compile can take up to a day to show.
 *
 * `metric_calculation_failed` reports each metric whose latest calculation failed, from the
 * latest finished calculation that the results page shows. It leaves out a metric that
 * `metric_cannot_compile` reports. The subcode is the kind of the first failure: `busy`,
 * `query_limit` (the query reached the read, memory, time or length limit), `settings` (a setting of
 * the metric or the experiment), `not_enough_data`, `experiment_too_old` (the experiment
 * started too long ago to calculate again) or `unexpected_error`. Each metric is in the
 * `evidence` keys `metric_N`, `metric_N_role`, `metric_N_failure` (the kind), `metric_N_error`
 * (the limit, or the family of a setting) and `metric_N_message` (only a message that PostHog
 * wrote for users), and `calculated_at` is when the calculation finished. It is a
 * warning when a primary metric fails for a kind that a change fixes (`query_limit`,
 * `settings`, `experiment_too_old`), also after the end, because the calculation after the fix
 * reads the events up to the end. It is info otherwise. When the first failure reached the
 * read, memory or time limit, `reason` names the cause that the calculation shows: `metric`
 * when another metric of the same calculation completed the same read of the exposures, or
 * `exposure_criteria` when every metric reached a limit and an exposure or test account filter
 * makes each query read all the properties of an event, person or group. `evidence.properties`
 * then names the filters. A query that read precomputed exposures doesn't apply those filters,
 * so it can't get `exposure_criteria`. It is null otherwise.
 *
 * `metric_all_zero` reports a metric that reads zero in every variant, from the same latest
 * finished calculation, so the results page shows "Not enough data yet" at any sample size.
 * Each side of a ratio that is zero in every variant counts on its own. It reads the stored
 * result and the project's event definitions, and no events. A primary metric needs 1,000
 * exposures in the result and 72 hours of data, because most zeros before that are outcomes
 * that take time. A retention metric counts those hours from the start of its retention
 * window. The subcode is the cause of the first metric: `blank_event` (an event with an empty
 * name), `event_stopped` (the project last received the event before launch, while ingestion
 * still records the project), `outlier_bound` (an upper outlier bound that is 0 while some
 * exposures have a value) or null when none shows a cause. `blank_event` and `outlier_bound`
 * also report a secondary metric, and need only 100 exposures and 12 hours of data, because
 * they read 0 at any traffic. A bound on the largest value of the exposures can't be 0 while
 * one has a value, so it is no cause. Neither is a bound on a metric with breakdowns, which
 * gets one bound per breakdown group. Until the end, the check leaves out a metric that uses an
 * event `metric_event_not_ingested` reports. Each metric, or side of a ratio, is in the
 * `evidence` keys `metric_N`, `metric_N_role`, `metric_N_side`, `metric_N_exposures` and
 * `metric_N_cause`. It is a warning for a primary metric. After the end it stays a warning only
 * for a cause that a setting fixes, because the calculation after the fix reads the events up
 * to the end. It is info otherwise.
 *
 * The severity of the `some_conditions_pinned` finding follows the largest share that the
 * users of the pinned release conditions make up among the users who got one variant from
 * the flag, in the last 7 days, or since launch or the flag's last save if later. It reads
 * the flag's calls that name the matched condition, not the experiment's exposure criteria:
 * info up to 5%, warning above, and no finding under 1% when at least half of the calls
 * that returned a variant name a condition. The finding is info when the share is unknown,
 * and `reason` says why: `not_measured` (for example an API key without
 * `query:read`, or a caller denied a flag call property), `too_few_people` (under 100), or
 * `evaluated_outside_flag_service` (most calls come from local evaluation, a bootstrap or
 * the caller's own assignment). A pin to a variant with 0% in the split adds an info,
 * because that variant's results show only the pinned users, unless the experiment
 * excludes the variant from the analysis.
 *
 * Two findings say that the variants are assigned outside PostHog, as info. A running
 * experiment whose flag has a 0% rollout gets `assigned_outside_flag_service` instead of
 * `running_but_no_rollout` when 10 or more people got a variant from flag calls without a
 * flag version that are no local evaluation, from an hour after the window starts. When
 * every condition that includes users pins the variant whose key one property holds,
 * `assigned_by_property` replaces `all_conditions_pinned`. When none of them includes
 * everyone, so that every other user gets no variant, `closed_to_matched_users` replaces it,
 * as a warning. A condition without filters, or with only filters that leave users out,
 * includes everyone.
 *
 * A draft whose flag has no recorded call gets the info `new_flag_no_traffic`. The record
 * is the flag's `last_called_at`, which a periodic task updates, so it trails a call. The
 * check reports `not_checked` when the organization's flag calls skip the events table,
 * and when the project has no active flag, because the web SDK then requests no flags.
 *
 * A running experiment whose flag is disabled gets `paused_from_experiment`, as info, when
 * its latest pause or resume since launch is a pause of the experiment. Otherwise it gets
 * `running_but_flag_disabled`, as a warning. A caller who can't view the linked flag's
 * history gets the warning, because the pause is not read. A draft whose flag is already
 * active with multiple variants gets `not_started_but_multiple_variants_rolled_out` as info.
 * An ended experiment whose flag is still active with multiple variants gets no finding when
 * another experiment on the flag is running or launched after the end. Otherwise it gets
 * `ended_flag_shared_with_draft` as info when a draft experiment uses the flag,
 * `ended_but_multiple_variants_rolled_out` as a warning when the flag's `last_called_at` is
 * after the end and within the last 3 days, and `ended_flag_not_called` as info when it is
 * not, from 3 days and an hour after the end, because `last_called_at` trails a call. Until
 * then without such a call, or when the organization's flag calls can't be read, it gets
 * `ended_flag_calls_unknown` as info.
 *
 * A running experiment whose first primary metric is a funnel gets the info
 * `early_significance` (subcode `below_detectable_effect`) when a significant variant's
 * difference is smaller than the smallest difference its sample can detect, while that
 * sample is below the one the running time estimate plans for the minimum detectable
 * effect. It reads the metric's current stored result, the one the results page shows
 * after its last calculation, and the running time calculator's formula.
 *
 * A running experiment with `only_count_matured_users` on gets the info
 * `metrics_not_matured` while it is younger than the conversion or retention window of
 * every primary metric, because no user can count for those metrics until a window passes.
 */
export const experimentsHealthRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentHealthApi> => {
    return apiMutator<ExperimentHealthApi>(getExperimentsHealthRetrieveUrl(projectId, id), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsHealthInputsRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/health_inputs/`
}

/**
 * Staff only. The inputs that the health checks read for this reader, to debug why a finding shows or not:
 * the context of the checks in `health`, the exposure query's answer that the exposure checks read, and facts
 * about the project from the setup context's providers (the team's experiment defaults and which SDKs call
 * flags). The exposure answer comes from the cache. When it is missing or stale, a calculation starts in the
 * background and `exposures.status` says so.
 */
export const experimentsHealthInputsRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentHealthInputsApi> => {
    return apiMutator<ExperimentHealthInputsApi>(getExperimentsHealthInputsRetrieveUrl(projectId, id), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsInSessionExposureRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/in_session_exposure/`
}

/**
 * How the recordings tab's in-session exposure scope reads on this experiment.
 *
 * Resolved through the same seam as the recordings query's `in_session` refusal, so the
 * scope control disables exactly what a query would be refused for, and the copy can say
 * when sessions are matched on the stamped flag property rather than on the exposure event.
 * Postgres reads only, so it can serve the tab's mount path.
 */
export const experimentsInSessionExposureRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentInSessionExposureApi> => {
    return apiMutator<ExperimentInSessionExposureApi>(getExperimentsInSessionExposureRetrieveUrl(projectId, id), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsLaunchCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/launch/`
}

/**
 * Launch a draft experiment.
 *
 * Validates the experiment is in draft state, activates its linked feature flag,
 * sets start_date to the current server time, and transitions the experiment to running.
 * Returns 400 if the experiment has already been launched or if the feature flag
 * configuration is invalid (e.g. fewer than 2 variants).
 */
export const experimentsLaunchCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsLaunchCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
    })
}

export const getExperimentsMetricsRecalculationCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/metrics_recalculation/`
}

/**
 * Trigger a batch recalculation of all metrics for this experiment.
 *
 * Returns 201 with the new pending recalculation, or 200 with the active one if a recalculation is
 * already pending or in progress for this experiment. An experiment that started too long ago gets 201 with
 * a run that is already failed: every metric carries the `recalculation_window_too_long` error in
 * `metric_errors`, no workflow starts, and a retry gets the same answer. A manual trigger within five
 * minutes after the latest completed run finished returns 429 with a Retry-After header. The response payload intentionally does not
 * include the `results` array — at POST time the workflow has just been queued and no per-metric
 * results exist yet. Clients should poll `GET metrics_recalculation/{id}/` for results as the workflow
 * progresses.
 */
export const experimentsMetricsRecalculationCreate = async (
    projectId: string,
    id: number,
    recalculateMetricsRequestApi?: RecalculateMetricsRequestApi,
    options?: RequestInit
): Promise<ExperimentMetricsRecalculationJobApi> => {
    return apiMutator<ExperimentMetricsRecalculationJobApi>(
        getExperimentsMetricsRecalculationCreateUrl(projectId, id),
        {
            ...options,
            method: 'POST',
            headers: { 'Content-Type': 'application/json', ...options?.headers },
            body: JSON.stringify(recalculateMetricsRequestApi),
        }
    )
}

export const getExperimentsMetricsRecalculationRetrieveUrl = (
    projectId: string,
    id: number,
    recalculationId: string
) => {
    return `/api/projects/${projectId}/experiments/${id}/metrics_recalculation/${recalculationId}/`
}

/**
 * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
 *
 * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
 * decorator on serializer methods and converts them into the same responses the viewset path
 * produces (see decorators._result_to_response), so both paths share one contract.
 */
export const experimentsMetricsRecalculationRetrieve = async (
    projectId: string,
    id: number,
    recalculationId: string,
    options?: RequestInit
): Promise<ExperimentMetricsRecalculationRunApi> => {
    return apiMutator<ExperimentMetricsRecalculationRunApi>(
        getExperimentsMetricsRecalculationRetrieveUrl(projectId, id, recalculationId),
        {
            ...options,
            method: 'GET',
        }
    )
}

export const getExperimentsMetricsRecalculationLatestRetrieveUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/metrics_recalculation/latest/`
}

/**
 * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
 *
 * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
 * decorator on serializer methods and converts them into the same responses the viewset path
 * produces (see decorators._result_to_response), so both paths share one contract.
 */
export const experimentsMetricsRecalculationLatestRetrieve = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentMetricsRecalculationLatestApi> => {
    return apiMutator<ExperimentMetricsRecalculationLatestApi>(
        getExperimentsMetricsRecalculationLatestRetrieveUrl(projectId, id),
        {
            ...options,
            method: 'GET',
        }
    )
}

export const getExperimentsMigrateCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/migrate/`
}

/**
 * Move a legacy experiment onto the new experiments engine.
 *
 * Creates a new experiment with the same configuration and its metrics converted
 * to the new format, and returns it. Legacy experiments no longer show results,
 * so this is how to get results for one. The legacy experiment is left untouched,
 * so the project ends up with two experiments. Both point at the same feature
 * flag, so no new rollout is needed and users keep the variant they already have.
 *
 * Legacy shared metrics used by the experiment are converted as part of the same
 * call. Each one gets a new shared metric, and the new experiment links to that.
 *
 * Calling this again returns the experiment created the first time instead of
 * making another copy.
 *
 * Returns 400 if the experiment already uses the new engine.
 */
export const experimentsMigrateCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsMigrateCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
    })
}

export const getExperimentsPauseCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/pause/`
}

/**
 * Pause a running experiment.
 *
 * Deactivates the linked feature flag so it is no longer returned by the
 * /decide endpoint. Users fall back to the application default (typically
 * the control experience), and no new exposure events are recorded (i.e.
 * $feature_flag_called is not fired).
 * Returns 400 if the experiment is not running or is already paused.
 */
export const experimentsPauseCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsPauseCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
    })
}

export const getExperimentsRecalculateTimeseriesCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/recalculate_timeseries/`
}

/**
 * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
 *
 * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
 * decorator on serializer methods and converts them into the same responses the viewset path
 * produces (see decorators._result_to_response), so both paths share one contract.
 */
export const experimentsRecalculateTimeseriesCreate = async (
    projectId: string,
    id: number,
    experimentApi: NonReadonly<ExperimentApi>,
    options?: RequestInit
): Promise<void> => {
    return apiMutator<void>(getExperimentsRecalculateTimeseriesCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentApi),
    })
}

export const getExperimentsResetCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/reset/`
}

/**
 * Reset an experiment back to draft state.
 *
 * Clears start/end dates, conclusion, archived flag, and any flag-cleanup
 * task pointer. The feature flag is left unchanged — users continue to see
 * their assigned variants.
 *
 * Previously collected events still exist but won't be included in
 * results unless the start date is manually adjusted after re-launch.
 *
 * Returns 400 if the experiment is already in draft state.
 */
export const experimentsResetCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsResetCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
    })
}

export const getExperimentsResumeCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/resume/`
}

/**
 * Resume a paused experiment.
 *
 * Reactivates the linked feature flag so it is returned by /decide again.
 * Users are re-bucketed deterministically into the same variants they had
 * before the pause, and exposure tracking resumes.
 * Returns 400 if the experiment is not running or is not paused.
 */
export const experimentsResumeCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsResumeCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
    })
}

export const getExperimentsRunningTimeTargetRetrieveUrl = (
    projectId: string,
    id: number,
    params?: ExperimentsRunningTimeTargetRetrieveParams
) => {
    const normalizedParams = new URLSearchParams()

    Object.entries(params || {}).forEach(([key, value]) => {
        if (value !== undefined) {
            normalizedParams.append(key, value === null ? 'null' : String(value))
        }
    })

    const stringifiedParams = normalizedParams.toString()

    return stringifiedParams.length > 0
        ? `/api/projects/${projectId}/experiments/${id}/running_time_target/?${stringifiedParams}`
        : `/api/projects/${projectId}/experiments/${id}/running_time_target/`
}

/**
 * The target sample of the experiment's running time estimate, which the experiment page's header compares
 * with the exposures so far, and what the experiment can detect over time.
 *
 * In manual running time mode it is the saved target. Otherwise it is sized from the first primary metric's
 * current result: the variance the analysis uses (with CUPED when the analysis applied it) and the flag's
 * traffic split, so that the comparison of each variant with the control reaches the minimum detectable effect.
 */
export const experimentsRunningTimeTargetRetrieve = async (
    projectId: string,
    id: number,
    params?: ExperimentsRunningTimeTargetRetrieveParams,
    options?: RequestInit
): Promise<RunningTimeTargetApi> => {
    return apiMutator<RunningTimeTargetApi>(getExperimentsRunningTimeTargetRetrieveUrl(projectId, id, params), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsSessionBucketsCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/session_buckets/`
}

/**
 * Session recordings of this experiment matching a bucket.
 *
 * Answers the questions a recordings query can't express on its own — "fired any of these
 * metrics", "fired none of them", "was exposed but never completed the funnel in this
 * session" — by returning a bounded, most-recent-first list of session IDs to pass back as
 * a recordings query's session_ids. POST because the metric list doesn't fit a query
 * string; the endpoint only reads.
 *
 * Session-scoped and goal-free: the set describes what happened in each session, while the
 * experiment analysis counts per person over the whole run window. A session can be in the
 * drop-off bucket while the same person converts in a later one.
 */
export const experimentsSessionBucketsCreate = async (
    projectId: string,
    id: number,
    experimentSessionBucketRequestApi: ExperimentSessionBucketRequestApi,
    options?: RequestInit
): Promise<ExperimentSessionBucketResponseApi> => {
    return apiMutator<ExperimentSessionBucketResponseApi>(getExperimentsSessionBucketsCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentSessionBucketRequestApi),
    })
}

export const getExperimentsSessionEventDeltasCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/session_event_deltas/`
}

/**
 * The recordings worth watching for this experiment, grouped into cards.
 *
 * Each card is one sentence and the recordings that back it: an event one variant did clearly
 * more than the others, an error signal concentrated in one variant, or a shortcut to a
 * metric event happening on screen. Every card's count is a count of recordings that actually
 * exist, so handing its session ids to the recordings list can't come back empty. POST to
 * take the same throttle and cache posture as the other reads in this family rather than
 * because it carries a body: it takes no parameters, and it only reads.
 *
 * It reports no effect size. Cards carry a direction and a band rather than a rate, a ratio
 * or a person count: the experiment's results already state magnitudes, computed per person
 * over the whole run window, and this reads one session per person over a clamped one. Two
 * numbers for the same event would read as a contradiction, so this surface states none. That
 * is what lets a card sit on one of the experiment's own metric events, which it names, so a
 * reader is sent to the results rather than given a second answer.
 */
export const experimentsSessionEventDeltasCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentSessionEventDeltaResponseApi> => {
    return apiMutator<ExperimentSessionEventDeltaResponseApi>(
        getExperimentsSessionEventDeltasCreateUrl(projectId, id),
        {
            ...options,
            method: 'POST',
        }
    )
}

export const getExperimentsShipVariantCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/ship_variant/`
}

/**
 * Ship a variant and (optionally) end the experiment.
 *
 * Updates the feature flag so the selected variant gets 100% of the variant
 * distribution. By default, existing release conditions on the flag are preserved
 * untouched — the variant is served only to users who already match them. Pass
 * ``release_to_everyone: true`` to also prepend a catch-all release condition
 * that rolls the variant out to 100% of users (overrides any existing release
 * conditions on the flag).
 *
 * Can be called on both running and stopped experiments. If the experiment is
 * still running, it will also be ended (end_date set and status marked as stopped).
 * If the experiment has already ended, only the flag is rewritten - this supports
 * the "end first, ship later" workflow.
 *
 * If an approval policy requires review before changes on the flag take effect,
 * the API returns 409 with a change_request_id. The experiment is NOT ended until
 * the change request is approved and the user retries.
 *
 * Returns 400 if the experiment is in draft state, the variant_key is not found
 * on the flag, or the experiment has no linked feature flag.
 */
export const experimentsShipVariantCreate = async (
    projectId: string,
    id: number,
    shipVariantApi: ShipVariantApi,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsShipVariantCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(shipVariantApi),
    })
}

export const getExperimentsTimeseriesResultsRetrieveUrl = (
    projectId: string,
    id: number,
    params: ExperimentsTimeseriesResultsRetrieveParams
) => {
    const normalizedParams = new URLSearchParams()

    Object.entries(params || {}).forEach(([key, value]) => {
        if (value !== undefined) {
            normalizedParams.append(key, value === null ? 'null' : String(value))
        }
    })

    const stringifiedParams = normalizedParams.toString()

    return stringifiedParams.length > 0
        ? `/api/projects/${projectId}/experiments/${id}/timeseries_results/?${stringifiedParams}`
        : `/api/projects/${projectId}/experiments/${id}/timeseries_results/`
}

/**
 * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
 *
 * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
 * decorator on serializer methods and converts them into the same responses the viewset path
 * produces (see decorators._result_to_response), so both paths share one contract.
 */
export const experimentsTimeseriesResultsRetrieve = async (
    projectId: string,
    id: number,
    params: ExperimentsTimeseriesResultsRetrieveParams,
    options?: RequestInit
): Promise<void> => {
    return apiMutator<void>(getExperimentsTimeseriesResultsRetrieveUrl(projectId, id, params), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsUnarchiveCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/unarchive/`
}

/**
 * Unarchive an archived experiment.
 *
 * Restores the experiment to the default list view. Returns 400 if the
 * experiment is not currently archived.
 */
export const experimentsUnarchiveCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsUnarchiveCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
    })
}

export const getExperimentsUnfreezeExposureCreateUrl = (projectId: string, id: number) => {
    return `/api/projects/${projectId}/experiments/${id}/unfreeze_exposure/`
}

/**
 * Reopen enrollment on an exposure-frozen experiment.
 *
 * Removes the snapshot-cohort condition and freeze markers from every release
 * group, restoring the flag's original targeting: new users can enroll again
 * and already-enrolled users keep their assigned variant. The snapshot cohort
 * is soft-deleted. The serialized status returns to 'running'.
 *
 * Returns 400 if the experiment is not running or its exposure is not frozen.
 */
export const experimentsUnfreezeExposureCreate = async (
    projectId: string,
    id: number,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsUnfreezeExposureCreateUrl(projectId, id), {
        ...options,
        method: 'POST',
    })
}

export const getExperimentsBulkUpdateTagsCreateUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiments/bulk_update_tags/`
}

/**
 * Bulk update tags on multiple objects.
 *
 * PAT access: this action has no ``required_scopes=`` on the decorator —
 * inheriting viewsets must add ``"bulk_update_tags"`` to their
 * ``scope_object_write_actions`` list to accept personal API keys.
 * Without that opt-in, ``APIScopePermission`` rejects PAT requests with
 * "This action does not support personal API key access". Done per-viewset
 * so granting ``<scope>:write`` for one resource doesn't leak access to
 * sibling resources that share this mixin.
 *
 * Accepts:
 * - {"ids": [...], "action": "add"|"remove"|"set", "tags": ["tag1", "tag2"]}
 *
 * Actions:
 * - "add": Add tags to existing tags on each object
 * - "remove": Remove specific tags from each object
 * - "set": Replace all tags on each object with the provided list
 */
export const experimentsBulkUpdateTagsCreate = async (
    projectId: string,
    bulkUpdateTagsRequestApi: BulkUpdateTagsRequestApi,
    options?: RequestInit
): Promise<BulkUpdateTagsResponseApi> => {
    return apiMutator<BulkUpdateTagsResponseApi>(getExperimentsBulkUpdateTagsCreateUrl(projectId), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(bulkUpdateTagsRequestApi),
    })
}

export const getExperimentsCalculateRunningTimeCreateUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiments/calculate_running_time/`
}

/**
 * Estimate the recommended sample size and running time for an experiment.
 *
 * Pure statistical calculation — does not read or write any experiment. Pass the metric type, a
 * minimum detectable effect, and either a baseline value or raw baseline statistics. When
 * `exposure_rate_per_day` is provided, the response also includes the estimated running time in days.
 */
export const experimentsCalculateRunningTimeCreate = async (
    projectId: string,
    runningTimeCalculationInputApi: RunningTimeCalculationInputApi,
    options?: RequestInit
): Promise<RunningTimeCalculationResultApi> => {
    return apiMutator<RunningTimeCalculationResultApi>(getExperimentsCalculateRunningTimeCreateUrl(projectId), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(runningTimeCalculationInputApi),
    })
}

export const getExperimentsCreateFromPromptCreateUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiments/create_from_prompt/`
}

/**
 * Create an experiment that compares N versions of an LLM prompt using a metric template.
 *
 * The user picks 2+ versions of an existing LLMPrompt and 1+ metric templates
 * (cost / latency / eval_pass_rate). The endpoint builds the matching variants
 * (control + test-N, each named after its prompt version) and attaches one
 * metric per selected template, each scoped to the prompt's $ai_prompt_name.
 * Resulting experiment is in draft state.
 */
export const experimentsCreateFromPromptCreate = async (
    projectId: string,
    createFromPromptInputApi: CreateFromPromptInputApi,
    options?: RequestInit
): Promise<ExperimentApi> => {
    return apiMutator<ExperimentApi>(getExperimentsCreateFromPromptCreateUrl(projectId), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(createFromPromptInputApi),
    })
}

export const getExperimentsMatchingIdsRetrieveUrl = (
    projectId: string,
    params?: ExperimentsMatchingIdsRetrieveParams
) => {
    const normalizedParams = new URLSearchParams()

    Object.entries(params || {}).forEach(([key, value]) => {
        if (value !== undefined) {
            normalizedParams.append(key, value === null ? 'null' : String(value))
        }
    })

    const stringifiedParams = normalizedParams.toString()

    return stringifiedParams.length > 0
        ? `/api/projects/${projectId}/experiments/matching_ids/?${stringifiedParams}`
        : `/api/projects/${projectId}/experiments/matching_ids/`
}

/**
 * Get IDs of all experiments matching the current list filters.
 * Accepts the same query params as the list endpoint and returns only
 * IDs of experiments the user has permission to edit.
 */
export const experimentsMatchingIdsRetrieve = async (
    projectId: string,
    params?: ExperimentsMatchingIdsRetrieveParams,
    options?: RequestInit
): Promise<ExperimentMatchingIdsResponseApi> => {
    return apiMutator<ExperimentMatchingIdsResponseApi>(getExperimentsMatchingIdsRetrieveUrl(projectId, params), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsPromptTemplatesRetrieveUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiments/prompt_templates/`
}

/**
 * List the LLM metric templates that can be passed to `create_from_prompt`.
 */
export const experimentsPromptTemplatesRetrieve = async (
    projectId: string,
    options?: RequestInit
): Promise<ExperimentsPromptTemplatesRetrieve200Item[]> => {
    return apiMutator<ExperimentsPromptTemplatesRetrieve200Item[]>(
        getExperimentsPromptTemplatesRetrieveUrl(projectId),
        {
            ...options,
            method: 'GET',
        }
    )
}

export const getExperimentsSessionContextRetrieveUrl = (
    projectId: string,
    params: ExperimentsSessionContextRetrieveParams
) => {
    const normalizedParams = new URLSearchParams()

    Object.entries(params || {}).forEach(([key, value]) => {
        if (value !== undefined) {
            normalizedParams.append(key, value === null ? 'null' : String(value))
        }
    })

    const stringifiedParams = normalizedParams.toString()

    return stringifiedParams.length > 0
        ? `/api/projects/${projectId}/experiments/session_context/?${stringifiedParams}`
        : `/api/projects/${projectId}/experiments/session_context/`
}

/**
 * Resolve which experiments (and variants) a session recording saw. Variants come from the session's $feature_flag_called events and stamped $feature/<key> event properties — flag evaluation, which may differ from an experiment's exposure criteria.
 */
export const experimentsSessionContextRetrieve = async (
    projectId: string,
    params: ExperimentsSessionContextRetrieveParams,
    options?: RequestInit
): Promise<ExperimentSessionContextResponseApi> => {
    return apiMutator<ExperimentSessionContextResponseApi>(getExperimentsSessionContextRetrieveUrl(projectId, params), {
        ...options,
        method: 'GET',
    })
}

export const getExperimentsSessionContextsCreateUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiments/session_contexts/`
}

/**
 * Resolve experiment context for a batch of session recordings.
 *
 * Batch variant of `session_context`, used to prefetch the replay player's experiments
 * box for a whole recordings list in one request. POST because the id list doesn't fit a
 * query string; the endpoint only reads. Already-computed sessions are served from (and
 * cold ones written to) the same short-lived per-viewer cache the single-session endpoint
 * uses, so opening any prefetched recording renders its context instantly. Sessions whose
 * recording metadata doesn't exist yet are omitted from the response, as are recordings
 * the caller can't access and sessions beyond the batch's recording-day budget (each
 * distinct recording day costs its own set of ClickHouse scans, so only the most recent
 * days are computed per request).
 */
export const experimentsSessionContextsCreate = async (
    projectId: string,
    experimentSessionContextsRequestApi: ExperimentSessionContextsRequestApi,
    options?: RequestInit
): Promise<ExperimentSessionContextsResponseApi> => {
    return apiMutator<ExperimentSessionContextsResponseApi>(getExperimentsSessionContextsCreateUrl(projectId), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentSessionContextsRequestApi),
    })
}

export const getExperimentsSetupContextCreateUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiments/setup_context/`
}

/**
 * Facts about this project that decide how to configure a new experiment.
 *
 * Returns the team's experiment defaults, which SDKs call feature flags, traffic on a target
 * surface, the baseline of a candidate metric, how recent experiments were set up, and the
 * most reused shared metrics. Each section has its own status, so a slow or failed read
 * leaves the others valid. POST because the inputs describe a plan rather than a resource;
 * the endpoint only reads.
 */
export const experimentsSetupContextCreate = async (
    projectId: string,
    experimentSetupContextInputApi?: ExperimentSetupContextInputApi,
    options?: RequestInit
): Promise<ExperimentSetupContextResponseApi> => {
    return apiMutator<ExperimentSetupContextResponseApi>(getExperimentsSetupContextCreateUrl(projectId), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(experimentSetupContextInputApi),
    })
}

export const getExperimentsStatsRetrieveUrl = (projectId: string) => {
    return `/api/projects/${projectId}/experiments/stats/`
}

/**
 * Mixin for ViewSets to handle approval-gate exceptions raised from decorated serializers.
 *
 * Intercepts ApprovalRequired (409) and PolicyConflict (400) raised by the @approval_gate
 * decorator on serializer methods and converts them into the same responses the viewset path
 * produces (see decorators._result_to_response), so both paths share one contract.
 */
export const experimentsStatsRetrieve = async (projectId: string, options?: RequestInit): Promise<void> => {
    return apiMutator<void>(getExperimentsStatsRetrieveUrl(projectId), {
        ...options,
        method: 'GET',
    })
}