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.

258 KB
Raw Blame
import type { PostHog, PropertyMatchType, SupportedWebVitalsMetrics } from 'posthog-js'
import { LogLevel } from 'posthog-js/rrweb-plugin-console-record'
import { eventWithTime } from 'posthog-js/rrweb-types'
import { ComponentType, ReactNode } from 'react'
import { LayoutItem } from 'react-grid-layout'

import { LemonTableColumns } from '@posthog/lemon-ui'

import { PaginatedResponse } from 'lib/api'
import type { Describer } from 'lib/components/ActivityLog/humanizeActivity'
import { CommonFilters, HeatmapFilters, HeatmapFixedPositionMode } from 'lib/components/heatmaps/types'
import { HedgehogActorOptions } from 'lib/components/HedgehogMode/types'
import { SessionRecordingTriggerGroupsConfig, UrlTriggerConfig } from 'lib/components/IngestionControls/types'
import type { ProductSetupProbe } from 'lib/components/ProductEmptyState/setupProbes'
import { JSONContent } from 'lib/components/RichContentEditor/types'
import { DashboardCompatibleScenes } from 'lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import {
    BIN_COUNT_AUTO,
    ENTITY_MATCH_TYPE,
    FunnelLayout,
    OrganizationMembershipLevel,
    PROPERTY_MATCH_TYPE,
    PluginsAccessLevel,
    RETENTION_FIRST_EVER_OCCURRENCE,
    RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS,
    RETENTION_MEAN_NONE,
    RETENTION_RECURRING,
    ShownAsValue,
    TeamMembershipLevel,
} from 'lib/constants'
import { Dayjs, dayjs } from 'lib/dayjs'
import { AggregationAxisFormat } from 'lib/insights/aggregationAxisFormat'
import { PopoverProps } from 'lib/lemon-ui/Popover/Popover'
import type { ProjectSecretAPIKeyAllowedScope } from 'lib/scopes'
import { BehavioralFilterKey, BehavioralFilterType } from 'scenes/cohorts/CohortFilters/types'
import { BreakdownColorConfig } from 'scenes/dashboard/dashboardBreakdownColors'
import { Params, Scene, SceneConfig, SceneTab } from 'scenes/sceneTypes'
import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { SurveyRatingScaleValue, WEB_SAFE_FONTS } from 'scenes/surveys/constants'

import type {
    FlagEvaluationsModeEnumApi,
    OrganizationMemberNoticeApi,
    OrganizationTeamBasicApi,
    OrganizationNotificationLockApi,
    ProjectApi,
    SharingConfigurationApi,
    TeamFeatureFlagPolicyConfigApi,
} from '~/generated/core/api.schemas'
import { RootAssistantMessage } from '~/queries/schema/schema-assistant-messages'
import type {
    AnalyticsQueryResponseBase,
    CoreEvent,
    CurrencyCode,
    CustomerAnalyticsConfig,
    DashboardFilter,
    DataWarehouseManagedViewsetKind,
    DataWarehouseSavedQueryOrigin,
    DatabaseSchemaField,
    ExperimentExposureCriteria,
    ExperimentFunnelsQuery,
    ExperimentMetric,
    ExperimentTrendsQuery,
    FileSystemIconType,
    FileSystemImport,
    EndpointQueryNode,
    HogQLQuery,
    HogQLQueryModifiers,
    HogQLVariable,
    InsightVizNode,
    MarketingAnalyticsConfig,
    Node,
    NodeKind,
    ProductItemCategory,
    ProductKey,
    QueryScanSummary,
    QuerySchema,
    QueryStatus,
    QuickFilterContext,
    QuickFilterType,
    RecordingOrder,
    RecordingsQuery,
    ResolvedDateRangeResponse,
    RevenueAnalyticsConfig,
    SharingConfigurationSettings,
    TileFilters,
    UserUIConfiguration,
} from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'

import type { ScopeObjectEnumApi } from 'products/access_control/frontend/generated/api.schemas'
import { AlertType } from 'products/alerts/frontend/types'
import type { BatchExportApi } from 'products/batch_exports/frontend/generated/api.schemas'
import type { CohortRealtimeReadinessApi } from 'products/cohorts/frontend/generated/api.schemas'
import type { DashboardTileGroupApi } from 'products/dashboards/frontend/generated/api.schemas'
import {
    type LineageIssueApi,
    type NodeApiSuspended,
    type NodeEndpointApi,
    NodeTypeEnumApi,
    type WarehouseColumnAnnotationDescriptionSourceEnumApi,
} from 'products/data_modeling/frontend/generated/api.schemas'
import type {
    DataWarehouseSavedQueryApi,
    DataWarehouseSavedQueryApiSuspended,
    SyncFrequencyBoundsApi,
} from 'products/data_warehouse/frontend/generated/api.schemas'
import type { ExperimentFeatureFlagInputApi } from 'products/experiments/frontend/generated/api.schemas'
import type { IntegrationConfigApi } from 'products/integrations/frontend/generated/api.schemas'
import type { CommentSlackThreadRefApi } from 'products/platform_features/frontend/generated/api.schemas'
import type { InsightFilterOverrideContextApi } from 'products/product_analytics/frontend/generated/api.schemas'
import type { AIPromptConfigApi, DeliveryConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'
import type { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
import type {
    IncrementalSyncBlockedReasonEnumApi,
    RowFilterColumnApi,
} from 'products/warehouse_sources/frontend/generated/api.schemas'
import { CyclotronInputType } from 'products/workflows/frontend/Workflows/hogflows/steps/types'
import type { HogFlow } from 'products/workflows/frontend/Workflows/hogflows/types'

import { PluginConfigSchema } from './legacy-plugin-scaffold'
import { InferredSelector } from './toolbar/shared/product-tours/elementInference'

export enum ConversionRateInputType {
    MANUAL = 'manual',
    AUTOMATIC = 'automatic',
}

/** Type alias for number to be reflected as integer in json-schema. */
/** @asType integer */
type integer = number

// Keep this in sync with backend constants/features/{product_name}.yml

export enum AvailableFeature {
    APPS = 'apps',
    SLACK_INTEGRATION = 'slack_integration',
    MICROSOFT_TEAMS_INTEGRATION = 'microsoft_teams_integration',
    DISCORD_INTEGRATION = 'discord_integration',
    ZAPIER = 'zapier',
    APP_METRICS = 'app_metrics',
    DATA_PIPELINES = 'data_pipelines',
    RECORDINGS_PLAYLISTS = 'recordings_playlists',
    SESSION_REPLAY_DATA_RETENTION = 'session_replay_data_retention',
    LOGS_RETENTION_30D = 'logs_retention_30d',
    CONSOLE_LOGS = 'console_logs',
    RECORDINGS_PERFORMANCE = 'recordings_performance',
    SESSION_REPLAY_NETWORK_PAYLOADS = 'session_replay_network_payloads',
    RECORDINGS_FILE_EXPORT = 'recordings_file_export',
    SESSION_REPLAY_SAMPLING = 'session_replay_sampling',
    REPLAY_RECORDING_DURATION_MINIMUM = 'replay_recording_duration_minimum',
    REPLAY_FEATURE_FLAG_BASED_RECORDING = 'replay_feature_flag_based_recording',
    REPLAY_MASK_SENSITIVE_DATA = 'replay_mask_sensitive_data',
    REPLAY_SHARING_EMBEDDING = 'replay_sharing_embedding',
    REPLAY_PRODUCT_ANALYTICS_INTEGRATION = 'replay_product_analytics_integration',
    REPLAY_FILTER_PERSON_PROPERTIES = 'replay_filter_person_properties',
    REPLAY_FILTER_EVENTS = 'replay_filter_events',
    REPLAY_DOM_EXPLORER = 'replay_dom_explorer',
    WORKS_WITH_POSTHOG_JS = 'works_with_posthog_js',
    REPLAY_AUTOMATIC_PLAYLISTS = 'replay_automatic_playlists',
    MOBILE_REPLAY = 'mobile_replay',
    GROUP_ANALYTICS = 'group_analytics',
    SURVEYS_UNLIMITED_SURVEYS = 'surveys_unlimited_surveys',
    SURVEYS_ALL_QUESTION_TYPES = 'surveys_all_question_types',
    SURVEYS_MULTIPLE_QUESTIONS = 'surveys_multiple_questions',
    SURVEYS_USER_TARGETING = 'surveys_user_targeting',
    SURVEYS_USER_SAMPLING = 'surveys_user_sampling',
    SURVEYS_STYLING = 'surveys_styling',
    SURVEYS_TEXT_HTML = 'surveys_text_html',
    SURVEYS_API_MODE = 'surveys_api_mode',
    SURVEYS_RESULTS_ANALYSIS = 'surveys_results_analysis',
    SURVEYS_TEMPLATES = 'surveys_templates',
    SURVEYS_DATA_RETENTION = 'surveys_data_retention',
    SURVEYS_LINK_QUESTION_TYPE = 'surveys_link_question_type',
    SURVEYS_SLACK_NOTIFICATIONS = 'surveys_slack_notifications',
    SURVEYS_WAIT_PERIODS = 'surveys_wait_periods',
    SURVEYS_RECURRING = 'surveys_recurring',
    SURVEYS_EVENTS = 'surveys_events',
    SURVEYS_ACTIONS = 'surveys_actions',
    TRACKED_USERS = 'tracked_users',
    TEAM_MEMBERS = 'team_members',
    API_ACCESS = 'api_access',
    ORGANIZATIONS_PROJECTS = 'organizations_projects',
    ROLE_BASED_ACCESS = 'role_based_access',
    SOCIAL_SSO = 'social_sso',
    SAML = 'saml',
    OIDC = 'oidc',
    SCIM = 'scim',
    SSO_ENFORCEMENT = 'sso_enforcement',
    XAA_AUTHENTICATION = 'xaa_authentication',
    WHITE_LABELLING = 'white_labelling',
    COMMUNITY_SUPPORT = 'community_support',
    DEDICATED_SUPPORT = 'dedicated_support',
    EMAIL_SUPPORT = 'email_support',
    ACCOUNT_MANAGER = 'account_manager',
    TRAINING = 'training',
    CONFIGURATION_SUPPORT = 'configuration_support',
    TERMS_AND_CONDITIONS = 'terms_and_conditions',
    SECURITY_ASSESSMENT = 'security_assessment',
    BESPOKE_PRICING = 'bespoke_pricing',
    INVOICE_PAYMENTS = 'invoice_payments',
    BOOLEAN_FLAGS = 'boolean_flags',
    FEATURE_FLAGS_DATA_RETENTION = 'feature_flags_data_retention',
    MULTIVARIATE_FLAGS = 'multivariate_flags',
    PERSIST_FLAGS_CROSS_AUTHENTICATION = 'persist_flags_cross_authentication',
    FEATURE_FLAG_PAYLOADS = 'feature_flag_payloads',
    MULTIPLE_RELEASE_CONDITIONS = 'multiple_release_conditions',
    RELEASE_CONDITION_OVERRIDES = 'release_condition_overrides',
    TARGETING_BY_GROUP = 'targeting_by_group',
    LOCAL_EVALUATION_AND_BOOTSTRAPPING = 'local_evaluation_and_bootstrapping',
    FLAG_USAGE_STATS = 'flag_usage_stats',
    USER_OPT_IN = 'user_opt_in',
    INSTANT_ROLLBACKS = 'instant_rollbacks',
    EXPERIMENTATION = 'experimentation',
    GROUP_EXPERIMENTS = 'group_experiments',
    FUNNEL_EXPERIMENTS = 'funnel_experiments',
    SECONDARY_METRICS = 'secondary_metrics',
    STATISTICAL_ANALYSIS = 'statistical_analysis',
    PRODUCT_ANALYTICS_DATA_RETENTION = 'product_analytics_data_retention',
    PRODUCT_ANALYTICS_STANDARD_DATA_RETENTION = 'product_analytics_standard_data_retention',
    DASHBOARDS = 'dashboards',
    FUNNELS = 'funnels',
    GRAPHS_TRENDS = 'graphs_trends',
    PATHS = 'paths',
    INSIGHTS = 'insights',
    SUBSCRIPTIONS = 'subscriptions',
    ADVANCED_PERMISSIONS = 'advanced_permissions', // TODO: Remove this once access_control is propagated
    ACCESS_CONTROL = 'access_control',
    PROPERTY_ACCESS_CONTROL = 'property_access_control',
    INGESTION_TAXONOMY = 'ingestion_taxonomy',
    PATHS_ADVANCED = 'paths_advanced',
    CORRELATION_ANALYSIS = 'correlation_analysis',
    BEHAVIORAL_COHORT_FILTERING = 'behavioral_cohort_filtering',
    PRODUCT_ANALYTICS_RETENTION = 'product_analytics_retention',
    PRODUCT_ANALYTICS_STICKINESS = 'product_analytics_stickiness',
    AUTOCAPTURE = 'autocapture',
    DATA_VISUALIZATION = 'data_visualization',
    PRODUCT_ANALYTICS_SQL_QUERIES = 'product_analytics_sql_queries',
    TWOFA_ENFORCEMENT = '2fa_enforcement',
    AUDIT_LOGS = 'audit_logs',
    APPROVALS = 'approvals',
    HIPAA_BAA = 'hipaa_baa',
    CUSTOM_MSA = 'custom_msa',
    TWOFA = '2fa',
    PRIORITY_SUPPORT = 'priority_support',
    SUPPORT_RESPONSE_TIME = 'support_response_time',
    AUTOMATIC_PROVISIONING = 'automatic_provisioning',
    MANAGED_REVERSE_PROXY = 'managed_reverse_proxy',
    ALERTS = 'alerts',
    HIGH_FREQUENCY_ALERTS = 'high_frequency_alerts',
    REAL_TIME_ALERTS = 'real_time_alerts',
    DATA_COLOR_THEMES = 'data_color_themes',
    ORGANIZATION_INVITE_SETTINGS = 'organization_invite_settings',
    ORGANIZATION_SECURITY_SETTINGS = 'organization_security_settings',
    MEMBER_GOVERNANCE = 'member_governance',
    SSF = 'ssf',
    TOOLBAR_HEATMAPS = 'toolbar_heatmaps',
}

type AvailableFeatureUnion = `${AvailableFeature}`

export enum LicensePlan {
    Scale = 'scale',
    Enterprise = 'enterprise',
    Dev = 'dev',
    Cloud = 'cloud',
}

export enum BillingPlan {
    Free = 'free',
    Paid = 'paid',
    Teams = 'teams', // Legacy
    Boost = 'boost',
    Scale = 'scale',
    Enterprise = 'enterprise',
}

export enum StartupProgramLabel {
    YC = 'YC',
    Startup = 'Startup',
}

export enum Realm {
    Cloud = 'cloud',
    Demo = 'demo',
    SelfHostedPostgres = 'hosted',
    SelfHostedClickHouse = 'hosted-clickhouse',
}

export enum Region {
    US = 'US',
    EU = 'EU',
    DEV = 'DEV',
}

export type SSOProvider = 'google-oauth2' | 'github' | 'gitlab' | 'saml' | 'oidc'
export type LoginMethod = SSOProvider | 'password' | 'passkey' | null

export interface AuthBackends {
    'google-oauth2'?: boolean
    gitlab?: boolean
    github?: boolean
    saml?: boolean
    oidc?: boolean
}

export type ColumnChoice = string[] | 'DEFAULT'

export interface ColumnConfig {
    active: ColumnChoice
}

export type WithAccessControl = {
    user_access_level: AccessControlLevel
}

export enum AccessControlResourceType {
    Project = 'project',
    Organization = 'organization',
    Action = 'action',
    CustomerAnalytics = 'customer_analytics',
    CustomerTask = 'customer_task',
    DataCatalog = 'data_catalog',
    DataDeletion = 'data_deletion',
    FeatureFlag = 'feature_flag',
    Heatmap = 'heatmap',
    Insight = 'insight',
    Dashboard = 'dashboard',
    DashboardTemplate = 'dashboard_template',
    LlmAnalytics = 'llm_analytics',
    Evaluation = 'evaluation',
    Tagger = 'tagger',
    LlmSkill = 'llm_skill',
    LlmPlayground = 'llm_playground',
    AiObservabilityClusters = 'ai_observability_clusters',
    Notebook = 'notebook',
    Ticket = 'ticket',
    SessionRecording = 'session_recording',
    SharingConfiguration = 'sharing_configuration',
    Stamphog = 'stamphog',
    RevenueAnalytics = 'revenue_analytics',
    Survey = 'survey',
    Logs = 'logs',
    McpAnalytics = 'mcp_analytics',
    Metrics = 'metrics',
    Endpoint = 'endpoint',
    Workflow = 'hog_flow',
    EarlyAccessFeature = 'early_access_feature',
    ProductTour = 'product_tour',
    Experiment = 'experiment',
    ExperimentHoldout = 'experiment_holdout',
    ExperimentSavedMetric = 'experiment_saved_metric',
    Export = 'export',
    ExternalDataSource = 'external_data_source',
    WarehouseObjects = 'warehouse_objects',
    WarehouseTable = 'warehouse_table',
    WarehouseView = 'warehouse_view',
    WebAnalytics = 'web_analytics',
    MarketingAnalytics = 'marketing_analytics',
    ActivityLog = 'activity_log',
    BusinessKnowledge = 'business_knowledge',
    ErrorTracking = 'error_tracking',
    Tracing = 'tracing',
    ReplayScanner = 'replay_scanner',
    Toolbar = 'toolbar',
}

interface UserBaseType {
    uuid: string
    distinct_id: string
    first_name: string
    last_name?: string
    email: string
}

/* Type for User objects in nested serializers (e.g. created_by) */
export interface UserBasicType extends UserBaseType {
    is_email_verified?: any
    id: number
    hedgehog_config?: MinimalHedgehogConfig
    role_at_organization?: string | null
}

/**
 * A user can have scene dashboard choices for multiple teams
 * TODO does this only have the current team's choices?
 */
export interface SceneDashboardChoice {
    scene: DashboardCompatibleScenes
    dashboard: number | DashboardBasicType
}

export type UserTheme = 'light' | 'dark' | 'system'
export type UserShortcutPosition = 'above' | 'below' | 'hidden'
// Mirrors posthog.models.user.OnboardingSkippedReason. Kept as a union here to avoid a
// hard dependency on generated types; when adopting generated `UserApi`, switch to
// `OnboardingSkippedReasonEnumApi` from `~/generated/core/api.schemas`.
export type OnboardingSkippedReason = 'delegated' | 'later' | 'other' | 'provisioned' | 'connector' | null

/** Full User model. */
export interface UserType extends UserBaseType {
    date_joined: string
    notification_settings: NotificationSettings
    /** Settings an organization admin enforces, which the member cannot change back. */
    notification_locks?: OrganizationNotificationLockApi[]
    active_realtime_notification_types?: readonly string[]
    requires_credential_review?: boolean
    events_column_config: ColumnConfig
    anonymize_data: boolean
    allow_impersonation: boolean
    toolbar_mode: 'disabled' | 'toolbar'
    has_password: boolean
    id: number
    is_staff: boolean
    is_impersonated: boolean
    is_impersonated_until?: string
    is_impersonated_read_only?: boolean
    is_impersonated_reason?: string | null
    sensitive_session_expires_at: string
    organization: OrganizationType | null
    team: TeamBasicType | null
    organizations: OrganizationBasicType[]
    realm?: Realm
    is_email_verified?: boolean | null
    pending_email?: string | null
    /** Absent until the app context's full stage arrives. */
    is_2fa_enabled?: boolean
    has_social_auth: boolean
    /** Absent until the app context's full stage arrives. */
    has_sso_enforcement?: boolean
    shortcut_position: UserShortcutPosition
    has_seen_product_intro_for?: Record<string, boolean>
    hide_mcp_hints?: boolean
    /** Per-user UI customization. Null means no customization: every element is shown. */
    ui_configuration?: UserUIConfiguration | null
    scene_personalisation?: SceneDashboardChoice[]
    theme_mode?: UserTheme | null
    hedgehog_config?: HedgehogConfig
    allow_sidebar_suggestions?: boolean
    role_at_organization?: UserRole | null
    passkeys_enabled_for_2fa?: boolean
    onboarding_skipped_at?: string | null
    onboarding_skipped_reason?: OnboardingSkippedReason
    onboarding_skipped_organization_id?: string | null
    onboarding_delegated_to_invite?: string | null
    onboarding_delegated_to_organization_id?: string | null
    onboarding_delegation_accepted_at?: string | null
    is_organization_first_user?: boolean
    /** How many personal API keys this user may hold, from the `personal_api_keys` entitlement. */
    personal_api_keys_limit?: number
    pending_invites?: PendingInviteForCurrentUser[]
}

export interface PendingInviteForCurrentUser {
    id: string
    target_email: string
    organization_id: string
    organization_name: string
    created_at: string
}

export type HedgehogColorOptions =
    | 'green'
    | 'red'
    | 'blue'
    | 'purple'
    | 'dark'
    | 'light'
    | 'sepia'
    | 'invert'
    | 'invert-hue'
    | 'greyscale'

export type MinimalHedgehogConfig = {
    use_as_profile: boolean
    color: HedgehogActorOptions['color']
    skin: HedgehogActorOptions['skin']
    accessories: HedgehogActorOptions['accessories']
}

export type HedgehogConfig = {
    version: 2
    use_as_profile: boolean
    party_mode_enabled: boolean
    enabled: boolean
    actor_options: HedgehogActorOptions
}

export interface NotificationSettings {
    plugin_disabled: boolean
    project_weekly_digest_disabled: Record<string, boolean>
    all_weekly_digest_disabled: boolean
    error_tracking_issue_assigned: boolean
    error_tracking_weekly_digest: boolean
    error_tracking_weekly_digest_project_enabled?: Record<string, boolean>
    discussions_mentioned: boolean
    data_pipeline_error_threshold?: number
    project_api_key_exposed?: boolean
    ai_evaluation_disabled?: boolean
    workflow_suggestions?: boolean
    materialized_view_sync_failed?: boolean
    materialized_view_sync_failed_daily?: boolean
    materialized_view_sync_failed_immediate?: boolean
    web_analytics_weekly_digest: boolean
    web_analytics_weekly_digest_project_enabled?: Record<string, boolean>
    data_catalog_weekly_digest?: boolean
    approval_requested?: boolean
    approval_resolved?: boolean
    organization_member_join_email_disabled?: Record<string, boolean>
    realtime_notifications_disabled?: Record<string, Record<string, boolean>>
    pipeline_notifications_disabled?: Record<string, boolean>
    task_comments_slack_dm?: boolean
}

export interface WebAnalyticsDigestMetricChange {
    percent: number
    direction: 'Up' | 'Down'
    is_good: boolean
}

export interface WebAnalyticsDigestMetric {
    key: string
    label: string
    value: string
    change: WebAnalyticsDigestMetricChange | null
}

export interface WebAnalyticsDigestListItem {
    label: string
    value: string
}

export interface WebAnalyticsDigestMetadata {
    period_label: string
    project_name: string
    dashboard_url: string
    metrics: WebAnalyticsDigestMetric[]
    top_pages: WebAnalyticsDigestListItem[]
    top_sources: WebAnalyticsDigestListItem[]
}

export interface InAppNotification {
    id: string
    team_id: number | null
    notification_type: string
    priority: string
    title: string
    body: string
    read: boolean
    read_at: string | null
    resource_type: string | null
    resource_id: string
    target_type: string
    target_id: string
    source_url: string
    source_type: string | null
    source_id: string | null
    metadata: WebAnalyticsDigestMetadata | null
    created_at: string
}

/**
 * Transient realtime event signalling that a resource was edited through some channel
 * (UI, MCP, or API). Rides the same notifications SSE transport as InAppNotification but is
 * never persisted or shown in the inbox — an open editor uses it to refresh instead of
 * clobbering edits made elsewhere. Discriminated by `notification_type === 'resource_edited'`.
 */
export interface ResourceEditedEvent {
    notification_type: 'resource_edited'
    team_id: number
    resource_type: string
    resource_id: string
    updated_at: string
    actor_user_id: number | null
}

export interface PluginAccess {
    view: boolean
    install: boolean
    configure: boolean
}

export interface PersonalAPIKeyType {
    id: string
    label: string
    description?: string | null
    value?: string
    is_legacy_hashing: boolean
    mask_value?: string | null
    /** Full value, only present for the seeded local dev key when the backend reveal gate is on. */
    local_dev_value?: string | null
    created_at: string
    last_used_at: string | null
    last_rolled_at: string | null
    expires_at: string | null
    team_id: number
    user_id: string
    scopes: string[]
    scoped_organizations?: OrganizationType['id'][] | null
    scoped_teams?: TeamType['id'][] | null
}

export interface ProjectSecretAPIKeyRequest {
    label: string
    scopes: ProjectSecretAPIKeyAllowedScope[]
}

export interface OrganizationBasicType {
    id: string
    name: string
    slug: string
    logo_media_id: string | null
    membership_level: OrganizationMembershipLevel | null
    members_can_use_personal_api_keys: boolean
    allow_publicly_shared_resources: boolean
    is_active: boolean | null
    is_not_active_reason: string | null
    is_pending_deletion: boolean
}

interface OrganizationMetadata {
    instance_tag?: string
}

export interface OrganizationType extends OrganizationBasicType {
    membership_joined_at?: string | null
    created_at: string
    updated_at: string
    plugins_access_level: PluginsAccessLevel
    teams: (TeamBasicType & Partial<Pick<OrganizationTeamBasicApi, 'project_group'>>)[]
    projects: ProjectBasicType[]
    available_product_features: BillingFeatureType[]
    is_member_join_email_enabled: boolean
    customer_id: string | null
    enforce_2fa: boolean | null
    enforce_verified_domains: boolean | null
    is_ai_data_processing_approved?: boolean
    is_ai_training_opted_in?: boolean
    is_ai_training_locked?: boolean
    is_ai_training_cta_shown?: boolean
    has_signed_baa?: boolean
    members_can_invite?: boolean
    members_can_create_projects?: boolean
    members_can_use_personal_api_keys: boolean
    members_can_see_org_members?: boolean
    read_only_mcp_access?: boolean
    member_notice?: OrganizationMemberNoticeApi | null
    allow_publicly_shared_resources: boolean
    metadata?: OrganizationMetadata
    member_count: number
    default_anonymize_ips?: boolean
    default_role_id?: string | null
    uses_most_specific_access_resolution?: boolean | null
}

export interface OrganizationDomainType {
    id: string
    domain: string
    is_verified: boolean
    verified_at: string // Datetime
    verification_challenge: string
    jit_provisioning_enabled: boolean
    sso_enforcement: SSOProvider | ''
    scim_base_url?: string
}

/** Member properties relevant at both organization and project level. */
export interface BaseMemberType {
    id: string
    user: UserBasicType
    last_login: string | null
    joined_at: string
    updated_at: string
    is_2fa_enabled: boolean
    has_social_auth: boolean
}

export interface OrganizationMemberType extends BaseMemberType {
    /** Level at which the user is in the organization. */
    level: OrganizationMembershipLevel
    is_2fa_enabled: boolean
}

export interface OrganizationMemberScopedApiKeysResponse {
    has_keys: boolean
    has_keys_active_last_week: boolean
    keys: {
        name: string
        last_used_at: string | null
    }[]
}

/**
 * This interface is only used in the frontend for fusing organization member data.
 */
export interface FusedTeamMemberType extends BaseMemberType {
    /**
     * Level at which the user explicitly is in the project.
     * Null means that membership is implicit (when showing permitted members)
     * or that there's no membership at all (when showing addable members).
     */
    explicit_team_level: TeamMembershipLevel | null
    /** Level at which the user is in the organization. */
    organization_level: OrganizationMembershipLevel
    /** Effective level of the user within the project. */
    level: OrganizationMembershipLevel
}

export interface ListOrganizationMembersParams {
    offset?: number
    limit?: number
    updated_after?: string
    search?: string
    /** Only members whose email is on this domain. */
    email_domain?: string
    /** Only members whose email is outside the organization's verified domains. */
    outside_verified_domains?: boolean
    /** Comma-separated membership levels to return, e.g. `1,8`. */
    levels?: string
}

export interface APIErrorType {
    type: 'authentication_error' | 'invalid_request' | 'server_error' | 'throttled_error' | 'validation_error'
    code: string
    detail: string
    attr: string | null
}

export interface EventUsageType {
    event: string
    usage_count: number
    volume: number
}

export interface PropertyUsageType {
    key: string
    usage_count: number
    volume: number
}

export interface ProjectBasicType {
    [key: string]: any
    id: number
    organization_id: string
    name: string
}

export interface TeamBasicType extends WithAccessControl {
    id: number
    uuid: string
    organization: string // Organization ID
    project_id: number
    api_token: string
    secret_api_token: string
    secret_api_token_backup: string
    name: string
    completed_snippet_onboarding: boolean
    has_completed_onboarding_for?: Record<string, boolean>
    ingested_event: boolean
    is_demo: boolean
    timezone: string
}

export interface ProjectType extends ProjectBasicType, Pick<ProjectApi, 'logo_media_id'> {
    created_at: string
    is_pending_deletion: boolean
    deletion_scheduled_at: string | null
    tags?: string[]
}

export interface TeamSurveyConfigType {
    appearance?: SurveyAppearance
}

export type SessionRecordingMaskingLevel = 'normal' | 'total-privacy' | 'free-love'

export type SessionRecordingRetentionPeriod = 'legacy' | '30d' | '90d' | '1y' | '5y'

export interface SessionRecordingMaskingConfig {
    maskAllInputs?: boolean
    maskTextSelector?: string
    blockSelector?: string
}

export enum ActivationTaskStatus {
    COMPLETED = 'completed',
    SKIPPED = 'skipped',
}

export interface ConversationsSettings {
    widget_enabled?: boolean
    widget_greeting_text?: string
    widget_color?: string
    widget_public_token?: string | null
    widget_domains?: string[] | null
    notification_recipients?: number[] | null
    widget_require_email?: boolean
    widget_collect_name?: boolean
    widget_identification_form_title?: string
    widget_identification_form_description?: string
    widget_placeholder_text?: string
    widget_position?: 'bottom_left' | 'bottom_right' | 'top_left' | 'top_right'
    slack_enabled?: boolean
    slack_team_id?: string | null
    slack_channel_id?: string | null
    slack_channel_name?: string | null
    slack_channel_ids?: string[] | null
    slack_ticket_emoji?: string | null
    slack_bot_icon_url?: string | null
    slack_bot_display_name?: string | null
    slack_notify_on_join?: boolean
    slack_notify_on_leave?: boolean
    slack_alert_channel_id?: string | null
    slack_nudge_enabled?: boolean
    /** Bot scopes Slack granted at install. Absent for installs authorized before we recorded them. */
    slack_scopes?: string[] | null
    email_enabled?: boolean
    teams_enabled?: boolean
    teams_team_id?: string | null
    teams_team_name?: string | null
    teams_channel_id?: string | null
    teams_channel_name?: string | null
    teams_channels?:
        | {
              team_id: string
              team_name?: string | null
              channel_id: string
              channel_name?: string | null
          }[]
        | null
    github_enabled?: boolean
    github_integration_id?: number | null
    github_repos?: string[] | null
    ai_suggestions_enabled?: boolean
    ai_diagnostics_enabled?: boolean
    ai_resolution_channels?: string[] | null
    ai_reply_modes?: Record<string, Record<string, 'private_note' | 'bot_reply'>> | null
    ai_reply_custom_instructions?: string | null
    docs_source?: 'posthog' | null
    ai_context_account_property_ids?: string[] | null
}

export interface LogsSettings {
    capture_console_logs?: boolean
    json_parse_logs?: boolean
    json_parse_logs_attribute_key?: string
    pii_scrub_logs?: boolean
    retention_days?: number
    retention_last_updated?: string
}

export interface TeamType extends TeamBasicType {
    created_at: string
    updated_at: string
    anonymize_ips: boolean
    app_urls: string[]
    recording_domains: string[]
    autocapture_opt_out: boolean
    session_recording_opt_in: boolean
    // These fields in the database accept null values and were previously set to NULL by default
    capture_console_log_opt_in: boolean | null
    capture_performance_opt_in: boolean | null
    capture_dead_clicks: boolean | null
    // a string representation of the decimal value between 0 and 1
    session_recording_sample_rate: string
    session_recording_minimum_duration_milliseconds: number | null
    session_recording_linked_flag: ({ variant?: string | null } & Pick<FeatureFlagBasicType, 'id' | 'key'>) | null
    session_recording_network_payload_capture_config:
        | { recordHeaders?: boolean; recordBody?: boolean }
        | undefined
        | null
    session_recording_masking_config: SessionRecordingMaskingConfig | undefined | null
    session_recording_retention_period: SessionRecordingRetentionPeriod | null
    session_replay_config: { record_canvas?: boolean } | undefined | null
    survey_config?: TeamSurveyConfigType
    logs_settings?: LogsSettings | null
    autocapture_exceptions_opt_in: boolean
    autocapture_web_vitals_opt_in?: boolean
    autocapture_web_vitals_allowed_metrics?: SupportedWebVitalsMetrics[]
    session_recording_url_trigger_config?: UrlTriggerConfig[]
    session_recording_url_blocklist_config?: UrlTriggerConfig[]
    session_recording_event_trigger_config?: string[]
    session_recording_trigger_match_type_config?: 'all' | 'any' | null
    session_recording_trigger_groups?: SessionRecordingTriggerGroupsConfig | null
    surveys_opt_in?: boolean
    heatmaps_opt_in?: boolean
    heatmaps_screenshot_secret?: string | null
    conversations_enabled?: boolean
    conversations_settings?: ConversationsSettings | null
    web_analytics_pre_aggregated_tables_enabled?: boolean
    web_analytics_pre_aggregated_tables_version?: 'v1' | 'v2'
    autocapture_exceptions_errors_to_ignore: string[]
    test_account_filters: AnyPropertyFilter[]
    test_account_filters_default_checked: boolean
    /** 0 or unset for Sunday, 1 for Monday. */
    week_start_day?: number
    path_cleaning_filters: PathCleaningFilter[]
    data_attributes: string[]
    person_display_name_properties: string[]
    has_group_types: boolean
    group_types: GroupType[]
    primary_dashboard: number | null // Dashboard shown on the project homepage
    home_tab_dashboard: number | null // Dashboard shown on the product analytics Home tab
    live_events_columns: string[] | null // Custom columns shown on the Live Events page
    live_events_token: string
    cookieless_server_hash_mode?: CookielessServerHashMode
    human_friendly_comparison_periods: boolean
    revenue_analytics_config: RevenueAnalyticsConfig
    onboarding_tasks?: {
        [key: string]: ActivationTaskStatus
    }

    /** Effective access level of the user in this specific team. Null if user has no access. */
    effective_membership_level: OrganizationMembershipLevel | null

    person_on_events_querying_enabled: boolean
    extra_settings?: Record<string, string | number | boolean | undefined>
    modifiers?: HogQLQueryModifiers
    default_modifiers?: HogQLQueryModifiers
    product_intents?: ProductIntentType[]
    default_data_theme?: number
    flags_persistence_default: boolean
    feature_flag_confirmation_enabled: boolean
    feature_flag_confirmation_message: string
    default_evaluation_contexts_enabled: boolean
    require_evaluation_contexts: boolean
    marketing_analytics_config: MarketingAnalyticsConfig
    core_events_config: { core_events: CoreEvent[] }
    base_currency: CurrencyCode
    managed_viewsets: Record<DataWarehouseManagedViewsetKind, boolean>
    flag_evaluations_mode: FlagEvaluationsModeEnumApi
    receive_org_level_activity_logs: boolean | null
    customer_analytics_config: CustomerAnalyticsConfig
    workflows_config: WorkflowsConfig
    // Optional so cached team objects from before this field shipped still typecheck.
    feature_flag_policy_config?: TeamFeatureFlagPolicyConfigApi
    business_model?: 'b2b' | 'b2c' | 'other' | null
}

export interface WorkflowsConfig {
    capture_workflows_engagement_events: boolean
    // Optional so cached team objects from before this field shipped still typecheck.
    email_tracking_consent_mode?: 'off' | 'opt_out' | 'opt_in'
    // Null uses the product default.
    workflow_task_rate_limit_per_day?: number | null
    workflow_task_team_rate_limit_per_day?: number | null
    // Optional so cached team objects from before these fields shipped still typecheck.
    email_utm_tags_enabled?: boolean
    email_utm_params?: Partial<Record<'utm_source' | 'utm_medium' | 'utm_campaign' | 'utm_content', string>>
    replay_vision_scan_rate_limit_per_day?: number | null
    replay_vision_scan_team_rate_limit_per_day?: number | null
    default_email_integration_id?: number | null
    // Null on either disables the marketing frequency cap.
    marketing_frequency_cap_max_messages?: number | null
    marketing_frequency_cap_window_days?: number | null
    // Null skips a capped marketing message at once instead of holding it for a free slot.
    marketing_frequency_cap_hold_hours?: number | null
}

export interface ProductIntentType {
    product_type: string
    created_at: string
    onboarding_completed_at?: string
}

// This type would be more correct without `Partial<TeamType>`, but it's only used in the shared dashboard/insight
// scenes, so not worth the refactor to use the `isAuthenticatedTeam()` check
export type TeamPublicType = Partial<TeamType> & Pick<TeamType, 'id' | 'uuid' | 'name' | 'timezone'>

export interface ActionType extends WithAccessControl {
    count?: number
    created_at: string
    deleted?: boolean
    id: number
    is_calculating?: boolean
    last_calculated_at?: string
    last_updated_at?: string // alias for last_calculated_at to achieve event and action parity
    name: string | null
    description?: string
    post_to_slack?: boolean
    slack_message_format?: string
    steps?: ActionStepType[]
    created_by: UserBasicType | null
    tags?: string[]
    verified?: boolean
    is_action?: true
    action_id?: number // alias of id to make it compatible with event definitions uuid
    bytecode?: any[]
    bytecode_error?: string
    pinned_at: string | null
    _create_in_folder?: string | null
    reference_count?: number
}

/** Sync with nodejs/src/types.ts */
export type ActionStepStringMatching = 'contains' | 'exact' | 'regex'

export interface ActionStepType {
    event?: string | null
    properties?: AnyPropertyFilter[]
    selector?: string | null
    /** @deprecated Only `selector` should be used now. */
    tag_name?: string
    text?: string | null
    /** @default StringMatching.Exact */
    text_matching?: ActionStepStringMatching | null
    href?: string | null
    /** @default ActionStepStringMatching.Exact */
    href_matching?: ActionStepStringMatching | null
    url?: string | null
    /** @default StringMatching.Contains */
    url_matching?: ActionStepStringMatching | null
    name?: string | null
}

export interface ElementType {
    attr_class?: string[]
    attr_id?: string
    attributes: Record<string, string>
    href?: string
    nth_child?: number
    nth_of_type?: number
    order?: number
    tag_name: string
    text?: string
}

// Keep the union literal so kea-typegen can inline its members; the runtime allowlist below
// is asserted to satisfy the same members so TypeScript fails the build if either side drifts.
export type ToolbarUserIntent =
    | 'add-action'
    | 'edit-action'
    | 'heatmaps'
    | 'add-experiment'
    | 'edit-experiment'
    | 'add-product-tour'
    | 'edit-product-tour'
    | 'preview-product-tour'

export const TOOLBAR_USER_INTENTS = [
    'add-action',
    'edit-action',
    'heatmaps',
    'add-experiment',
    'edit-experiment',
    'add-product-tour',
    'edit-product-tour',
    'preview-product-tour',
] as const satisfies readonly ToolbarUserIntent[]
export type ToolbarSource = 'url' | 'localstorage' | 'extension'
export type ToolbarVersion = 'toolbar'

export type ExperimentIdType = number | 'new' | 'web'

/* sync with posthog-js */
export interface ToolbarParams {
    /** @deprecated, not needed if `posthog` is passed as prop instead */
    apiURL?: string
    token?: string /** public posthog-js token */
    /** @deprecated Replaced by OAuth flow. Remove after September 2026. */
    temporaryToken?: string
    accessToken?: string /** OAuth access token (Bearer) */
    refreshToken?: string /** OAuth refresh token */
    clientId?: string /** OAuth client_id for token refresh */
    actionId?: number
    experimentId?: ExperimentIdType
    userIntent?: ToolbarUserIntent
    source?: ToolbarSource
    toolbarVersion?: ToolbarVersion
    instrument?: boolean
    distinctId?: string
    userEmail?: string
    dataAttributes?: string[]
    toolbarFlagsKey?: string
    productTourId?: string
    uiHost?: string /** PostHog app URL, used for OAuth and UI links */
}

export interface ToolbarProps extends ToolbarParams {
    posthog?: PostHog
    disableExternalStyles?: boolean
}

export type PathCleaningFilter = {
    /**
     * The replacement for the matched path. Use angle-bracket placeholders (`<id>`, `<uuid>`, `<slug>`)
     * by convention, or reuse a capture group from the regex with ClickHouse `replaceRegexpAll`
     * replacement syntax: `\1` to `\9` for a group and `\0` for the whole match.
     */
    alias?: string
    regex?: string
    order?: number
}

export type PropertyFilterBaseValue = string | number | bigint | boolean
export type PropertyFilterValue = PropertyFilterBaseValue | PropertyFilterBaseValue[] | null

/** Sync with nodejs/src/types.ts */
export enum PropertyOperator {
    Exact = 'exact',
    IsNot = 'is_not',
    IContains = 'icontains',
    NotIContains = 'not_icontains',
    StartsWith = 'starts_with',
    NotStartsWith = 'not_starts_with',
    EndsWith = 'ends_with',
    NotEndsWith = 'not_ends_with',
    Regex = 'regex',
    NotRegex = 'not_regex',
    GreaterThan = 'gt',
    GreaterThanOrEqual = 'gte',
    LessThan = 'lt',
    LessThanOrEqual = 'lte',
    IsSet = 'is_set',
    IsNotSet = 'is_not_set',
    IsDateExact = 'is_date_exact',
    IsDateBefore = 'is_date_before',
    IsDateAfter = 'is_date_after',
    Between = 'between',
    NotBetween = 'not_between',
    Minimum = 'min',
    Maximum = 'max',
    In = 'in',
    NotIn = 'not_in',
    IsCleanedPathExact = 'is_cleaned_path_exact',
    IsCleanedPathNotExact = 'is_cleaned_path_not_exact',
    FlagEvaluatesTo = 'flag_evaluates_to',
    SemverEq = 'semver_eq',
    SemverNeq = 'semver_neq',
    SemverGt = 'semver_gt',
    SemverGte = 'semver_gte',
    SemverLt = 'semver_lt',
    SemverLte = 'semver_lte',
    SemverTilde = 'semver_tilde',
    SemverCaret = 'semver_caret',
    SemverWildcard = 'semver_wildcard',
    IContainsMulti = 'icontains_multi',
    NotIContainsMulti = 'not_icontains_multi',
}

export enum SavedInsightsTabs {
    Home = 'home',
    All = 'all',
    Yours = 'yours',
    History = 'history',
    Alerts = 'alerts',
    Notifications = 'notifications',
}

export enum ReplayTabs {
    Home = 'home',
    Playlists = 'playlists',
    Settings = 'settings',
}

export type ReplayTab = {
    label: string
    key: ReplayTabs
    tooltip?: string
    tooltipDocLink?: string
    'data-attr'?: string
}

export enum ExperimentsTabs {
    All = 'all',
    Holdouts = 'holdouts',
    SharedMetrics = 'shared-metrics',
    History = 'history',
    Settings = 'settings',
}

// Values are URL path segments under /activity; `redirects` in scenes.ts keeps old ones working.
export enum ActivityTab {
    ExploreEvents = 'events',
    LiveEvents = 'live',
    ExploreSessions = 'sessions',
}

export enum ProgressStatus {
    Draft = 'draft',
    Running = 'running',
    Complete = 'complete',
}

export enum ExperimentStatus {
    Draft = 'draft',
    Running = 'running',
    Paused = 'paused',
    // Running with enrollment frozen to the already-exposed cohort while metrics keep flowing.
    // Derived from the feature flag, not stored — see Experiment.is_exposure_frozen.
    ExposureFrozen = 'exposure_frozen',
    Stopped = 'stopped',
}

export enum PropertyFilterType {
    /** Event metadata and fields on the clickhouse events table */
    Meta = 'meta',
    /** Event properties */
    Event = 'event',
    InternalEvent = 'internal_event',
    EventMetadata = 'event_metadata',
    /** Person properties */
    Person = 'person',
    /** Top-level columns on the persons table (e.g. created_at), not properties JSON */
    PersonMetadata = 'person_metadata',
    Element = 'element',
    /** Event property with "$feature/" prepended */
    Feature = 'feature',
    Session = 'session',
    Cohort = 'cohort',
    /** Person performed (or didn't perform) an event in a time window. ClickHouse-only — not evaluable by flags or CDP */
    Behavioral = 'behavioral',
    Recording = 'recording',
    LogEntry = 'log_entry',
    Group = 'group',
    HogQL = 'hogql',
    DataWarehouse = 'data_warehouse',
    DataWarehousePersonProperty = 'data_warehouse_person_property',
    ErrorTrackingIssue = 'error_tracking_issue',
    RevenueAnalytics = 'revenue_analytics',
    Account = 'account',
    /** Customer analytics account relationship — the key is the relationship definition id */
    AccountRelationship = 'account_relationship',
    /** Customer analytics account custom property — the key is the property definition id */
    AccountCustomProperty = 'account_custom_property',
    /** Feature flag dependency */
    Flag = 'flag',
    Log = 'log',
    LogAttribute = 'log_attribute',
    LogResourceAttribute = 'log_resource_attribute',
    MetricAttribute = 'metric_attribute',
    Span = 'span',
    SpanAttribute = 'span_attribute',
    SpanResourceAttribute = 'span_resource_attribute',
    WorkflowVariable = 'workflow_variable',
    Empty = 'empty',
}

/** Sync with nodejs/src/types.ts */
interface BasePropertyFilter {
    key: string
    value?: PropertyFilterValue
    label?: string
    type?: PropertyFilterType
}

/** Sync with nodejs/src/types.ts */
export interface EventPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Event
    /** @default 'exact' */
    operator: PropertyOperator
}

export interface EventMetadataPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.EventMetadata
    operator: PropertyOperator
}

export interface RevenueAnalyticsPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.RevenueAnalytics
    operator: PropertyOperator
}

export interface AccountRelationshipPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.AccountRelationship
    operator: PropertyOperator
}

export interface AccountCustomPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.AccountCustomProperty
    operator: PropertyOperator
}

/** Sync with nodejs/src/types.ts */
export interface PersonPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Person
    operator: PropertyOperator
}

export interface PersonMetadataPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.PersonMetadata
    operator: PropertyOperator
}

export interface DataWarehousePropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.DataWarehouse
    operator: PropertyOperator
}

export interface DataWarehousePersonPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.DataWarehousePersonProperty
    operator: PropertyOperator
}

export interface ErrorTrackingIssueFilter extends BasePropertyFilter {
    type: PropertyFilterType.ErrorTrackingIssue
    operator: PropertyOperator
}

/** Sync with nodejs/src/types.ts */
export interface ElementPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Element
    key: 'tag_name' | 'text' | 'href' | 'selector'
    operator: PropertyOperator
}

export interface SessionPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Session
    operator: PropertyOperator
}

/** Sync with nodejs/src/types.ts */
export interface CohortPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Cohort
    key: 'id'
    /**  @asType integer */
    value: number
    /** @default 'in' */
    operator: PropertyOperator
    cohort_name?: string
    /** Set by the feature flag API when the cohort is deleted or does not exist. */
    cohort_deleted?: boolean
    /** Set by the feature flag API when the cohort does not exist, so it cannot be restored. */
    cohort_missing?: boolean
}

export interface GroupPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Group
    group_type_index?: integer | null
    operator: PropertyOperator
    group_key_names?: Record<string, string>
}

/** The subset of cohort behavioral criteria supported by the inline `BehavioralPropertyFilter` */
export type InlineBehavioralType = BehavioralEventType.PerformEvent | BehavioralEventType.PerformMultipleEvents

/** Whether a behavioral filter's `key` refers to an event name or an action id */
export type BehavioralEventSource = 'events' | 'actions'

/** Filters persons on whether they performed an event in a time window, without a saved cohort. Event scope only. */
export interface BehavioralPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Behavioral
    value: InlineBehavioralType
    /** Event name, or action id when event_type is 'actions' */
    key: string
    event_type: BehavioralEventSource
    /** Match persons who did NOT satisfy the criterion. Not the same as a low count — zero-occurrence persons never match count operators */
    negation?: boolean
    /** Count comparison for performed_event_multiple, defaults to exact */
    operator?: PropertyOperator
    /**
     * Count threshold for performed_event_multiple
     * @asType integer
     */
    operator_value?: number
    /**
     * Relative time window size, paired with time_interval
     * @asType integer
     */
    time_value?: number
    time_interval?: TimeUnitType
    /** Absolute or relative (e.g. -30d) lower date bound — alternative to time_value/time_interval */
    explicit_datetime?: string
    explicit_datetime_to?: string
    /** Extra property filters the matching events must satisfy. Deliberately excludes nested behavioral/cohort filters and groups */
    event_filters?: (
        | EventPropertyFilter
        | PersonPropertyFilter
        | ElementPropertyFilter
        | FeaturePropertyFilter
        | HogQLPropertyFilter
    )[]
}

export type LogPropertyFilterType =
    | PropertyFilterType.Log
    | PropertyFilterType.LogAttribute
    | PropertyFilterType.LogResourceAttribute

export interface LogPropertyFilter extends BasePropertyFilter {
    type: LogPropertyFilterType
    operator: PropertyOperator
}

export interface MetricPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.MetricAttribute
    operator: PropertyOperator
}

export type SpanPropertyFilterType =
    | PropertyFilterType.Span
    | PropertyFilterType.SpanAttribute
    | PropertyFilterType.SpanResourceAttribute

export interface SpanPropertyFilter extends BasePropertyFilter {
    type: SpanPropertyFilterType
    operator: PropertyOperator
}

export interface FeaturePropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Feature
    operator: PropertyOperator
}

export interface FlagPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Flag
    /** Only flag_evaluates_to operator is allowed for flag dependencies */
    operator: PropertyOperator.FlagEvaluatesTo
    /** The key should be the flag ID */
    key: string
    /** The value can be true, false, or a variant name */
    value: boolean | string
}

export interface HogQLPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.HogQL
    key: string
}

export interface WorkflowVariablePropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.WorkflowVariable
    operator: PropertyOperator
}

export interface EmptyPropertyFilter {
    type?: PropertyFilterType.Empty
    value?: never
    operator?: never
    key?: never
}

export type AnyPropertyFilter =
    | EventPropertyFilter
    | PersonPropertyFilter
    | PersonMetadataPropertyFilter
    | ElementPropertyFilter
    | EventMetadataPropertyFilter
    | SessionPropertyFilter
    | CohortPropertyFilter
    | RecordingPropertyFilter
    | LogEntryPropertyFilter
    | GroupPropertyFilter
    | FeaturePropertyFilter
    | FlagPropertyFilter
    | HogQLPropertyFilter
    | EmptyPropertyFilter
    | DataWarehousePropertyFilter
    | DataWarehousePersonPropertyFilter
    | ErrorTrackingIssueFilter
    | LogPropertyFilter
    | MetricPropertyFilter
    | SpanPropertyFilter
    | RevenueAnalyticsPropertyFilter
    | AccountCustomPropertyFilter
    | WorkflowVariablePropertyFilter
    | BehavioralPropertyFilter

/** Any filter type supported by `property_to_expr(scope="person", ...)`. */
export type AnyPersonScopeFilter =
    | PersonPropertyFilter
    | PersonMetadataPropertyFilter
    | CohortPropertyFilter
    | HogQLPropertyFilter
    | EmptyPropertyFilter

export type AnyGroupScopeFilter = GroupPropertyFilter | HogQLPropertyFilter

export type AnyFilterLike = AnyPropertyFilter | PropertyGroupFilter | PropertyGroupFilterValue

export type SessionRecordingId = SessionRecordingType['id']

export interface RRWebRecordingConsoleLogPayload {
    level: LogLevel
    payload: (string | null)[]
    trace: string[]
}

export interface RRWebRecordingNetworkPayload {
    [key: number]: any
}

export interface RecordingConsoleLogBase {
    parsedPayload: string
    hash?: string // md5() on parsedPayload. Used for deduping console logs.
    count?: number // Number of duplicate console logs
    previewContent?: ReactNode // Content to show in first line
    fullContent?: ReactNode // Full content to show when item is expanded
    traceContent?: ReactNode // Url content to show on right side
    rawString: string // Raw text used for fuzzy search
    level: LogLevel
}

export type RecordingConsoleLog = RecordingConsoleLogBase & RecordingTimeMixinType

export type RecordingConsoleLogV2 = {
    timestamp: number
    windowId: number | undefined
    windowNumber?: number | '?' | undefined
    level: LogLevel
    content: string
    count?: number
    // JS code associated with the log - implicitly the empty array when not provided
    lines?: string[]
    // stack trace associated with the log - implicitly the empty array when not provided
    trace?: string[]
}

import type {
    EncodedRecordingSnapshot as _EncodedRecordingSnapshot,
    RecordingSegment as _RecordingSegment,
    RecordingSnapshot as _RecordingSnapshot,
    SessionRecordingSnapshotSource as _SessionRecordingSnapshotSource,
    SessionRecordingSnapshotSourceResponse as _SessionRecordingSnapshotSourceResponse,
} from '@posthog/replay-shared'

export type RecordingSegment = _RecordingSegment
export type EncodedRecordingSnapshot = _EncodedRecordingSnapshot
export type RecordingSnapshot = _RecordingSnapshot
export type SessionRecordingSnapshotSource = _SessionRecordingSnapshotSource
export type SessionRecordingSnapshotSourceResponse = _SessionRecordingSnapshotSourceResponse

export type SessionRecordingSnapshotParams = {
    source: 'blob_v2'
    start_blob_key?: string
    end_blob_key?: string
    blob_key?: string
} & {
    decompress?: false
}

export interface SessionRecordingSnapshotResponse {
    sources?: SessionRecordingSnapshotSource[]
    snapshots?: EncodedRecordingSnapshot[]
    replay_proxy_token?: string | null
    block_token?: string | null
    block_token_expires_at?: string | null
}

export interface SessionPlayerSnapshotData {
    snapshots?: RecordingSnapshot[]
    sources?: SessionRecordingSnapshotSource[]
    blob_keys?: string[]
}

export interface SessionPlayerData {
    person: PersonType | null
    segments: RecordingSegment[]
    bufferedToTime: number | null
    snapshotsByWindowId: Record<number, eventWithTime[]>
    durationMs: number
    start: Dayjs | null
    end: Dayjs | null
    fullyLoaded: boolean
    sessionRecordingId: SessionRecordingId
    sessionRetentionPeriodDays: number | null
}

export enum SessionRecordingUsageType {
    VIEWED = 'viewed',
    ANALYZED = 'analyzed',
    LOADED = 'loaded',
}

export enum SessionRecordingSidebarTab {
    OVERVIEW = 'overview',
    INSPECTOR = 'inspector',
    NETWORK_WATERFALL = 'network-waterfall',
    LINKED_ISSUES = 'linked-issues',
    SESSIONS = 'sessions',
    OBSERVATIONS = 'observations',
}

export enum SessionRecordingSidebarStacking {
    Vertical = 'vertical',
    Horizontal = 'horizontal',
}

export enum SessionPlayerState {
    READY = 'ready',
    BUFFER = 'buffer',
    PLAY = 'play',
    PAUSE = 'pause',
    SCRUB = 'scrub',
    SKIP = 'skip',
    SKIP_TO_MATCHING_EVENT = 'skip_to_matching_event',
    ERROR = 'error',
}

export type AutoplayDirection = 'newer' | 'older' | null

/** Sync with nodejs/src/types.ts */
export type ActionStepProperties =
    | EventPropertyFilter
    | PersonPropertyFilter
    | ElementPropertyFilter
    | CohortPropertyFilter

export interface RecordingPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.Recording
    key:
        | DurationType
        | 'snapshot_source'
        | 'visited_page'
        | 'comment_text'
        | 'click_count'
        | 'keypress_count'
        | 'mouse_activity_count'
    operator: PropertyOperator
}

export interface RecordingDurationFilter extends RecordingPropertyFilter {
    key: DurationType
    value: number
}

export interface LogEntryPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.LogEntry
    operator: PropertyOperator
}

export interface LogEntryPropertyFilter extends BasePropertyFilter {
    type: PropertyFilterType.LogEntry
    operator: PropertyOperator
}

export interface LogEntryLevelFilter extends LogEntryPropertyFilter {
    key: 'level'
    value: FilterableLogLevel[]
}
export interface LogEntryMessageFilter extends LogEntryPropertyFilter {
    key: 'message'
    value: string
}

export type DurationType = 'duration' | 'active_seconds' | 'inactive_seconds'
export type FilterableLogLevel = 'info' | 'warn' | 'error'

export interface LegacyRecordingFilters {
    date_from?: string | null
    date_to?: string | null
    events?: Record<string, any>[]
    actions?: Record<string, any>[]
    properties?: AnyPropertyFilter[]
    session_recording_duration?: RecordingDurationFilter
    duration_type_filter?: DurationType
    console_search_query?: LogEntryMessageFilter['value']
    console_logs?: LogEntryLevelFilter['value']
    snapshot_source?: AnyPropertyFilter | null
    filter_test_accounts?: boolean
    operand?: FilterLogicalOperator
}

export interface RecordingUniversalFilters {
    date_from?: string | null
    date_to?: string | null
    duration: RecordingDurationFilter[]
    filter_test_accounts?: boolean
    filter_group: UniversalFiltersGroup
    session_ids?: string[]
    person_uuid?: string
    order?: RecordingsQuery['order']
    order_direction?: RecordingsQuery['order_direction']
    limit?: RecordingsQuery['limit']
    recommended_only?: boolean
    event_match_scope?: RecordingsQuery['event_match_scope']
    /**
     * Server-resolved population narrowing (sessions of persons exposed to the experiment).
     * Not part of `filter_group`, so the filter-pill editor neither renders nor edits it;
     * it rides through conversions so saved filters and scanners keep the narrowing.
     */
    experiment_exposure?: RecordingsQuery['experiment_exposure']
}

export interface UniversalFiltersGroup {
    type: FilterLogicalOperator
    values: UniversalFiltersGroupValue[]
}

export type UniversalFiltersGroupValue = UniversalFiltersGroup | UniversalFilterValue
export type UniversalFilterValue = AnyPropertyFilter | ActionFilter

export type ErrorCluster = {
    cluster: number
    sample: string
    occurrences: number
    session_ids: string[]
    sparkline: Record<string, number>
    unique_sessions: number
    viewed: number
}
export type ErrorClusterResponse = ErrorCluster[] | null

export type EntityType = 'actions' | 'events' | 'data_warehouse' | 'new_entity' | 'groups'

export enum EntityTypes {
    ACTIONS = 'actions',
    EVENTS = 'events',
    DATA_WAREHOUSE = 'data_warehouse',
    GROUPS = 'groups',
}

export interface ActionFilter {
    type: EntityType
    id: string | number | null
    name?: string | null
    custom_name?: string | null
    index?: number
    order?: number
    optionalInFunnel?: boolean
    math?: string
    math_property?: string | null
    math_property_type?: TaxonomicFilterGroupType | null
    math_group_type_index?: integer | null
    math_hogql?: string | null
    properties?: AnyPropertyFilter[]
    days?: string[] // TODO: why was this added here?
    operator?: FilterLogicalOperator | null
    nestedFilters?:
        | {
              type?: EntityType
              id: string | number | null
              name?: string | null
              custom_name?: string | null
              index?: number
              order?: number
              optionalInFunnel?: boolean
          }[]
        | null
    /** Replay-only. When true, matches sessions that do NOT contain any event matching this entity */
    negation?: boolean
}

export interface PersonType {
    id?: string
    uuid?: string
    name?: string
    distinct_ids: string[]
    properties: Record<string, any>
    created_at?: string
    last_seen_at?: string
    is_identified?: boolean
}

export interface PersonListParams {
    properties?: AnyPropertyFilter[]
    search?: string
    cohort?: number
    distinct_id?: string
    include_total?: boolean // PostHog 3000-only
    limit?: number
    /** Names the ClickHouse query so `api.cancelQuery` can stop it. Up to 128 characters. */
    client_query_id?: string
}

export type SearchableEntity =
    | 'action'
    | 'cohort'
    | 'data_warehouse_view'
    | 'insight'
    | 'dashboard'
    | 'early_access_feature'
    | 'endpoint'
    | 'event_definition'
    | 'experiment'
    | 'feature_flag'
    | 'hog_flow'
    | 'notebook'
    | 'property_definition'
    | 'survey'

export type SearchListParams = {
    q?: string
    entities?: SearchableEntity[]
    include_counts?: boolean
}

export type SearchResultType = {
    result_id: string
    type: SearchableEntity
    rank: number | null
    extra_fields: Record<string, unknown>
    /** Resolved access level the user has for this object ('none' means no access); null when access controls don't apply */
    user_access_level?: AccessControlLevel | null
}

export type SearchResponse = {
    results: SearchResultType[]
    counts?: Record<SearchableEntity, number | null>
}

export type GroupListParams = {
    group_type_index: GroupTypeIndex
    search: string
    limit?: number
}

export type CreateGroupParams = {
    group_type_index: GroupTypeIndex
    group_key: string
    group_properties?: Record<string, any>
}

export interface MatchedRecordingEvent {
    uuid: string
    timestamp: string
}

export interface MatchedRecording {
    session_id?: string
    events: MatchedRecordingEvent[]
}

export interface CommonActorType {
    id: string | number
    properties: Record<string, any>
    /** @format date-time */
    created_at: string | null
    matched_recordings: MatchedRecording[]
    value_at_data_point: number | null
}

export interface PersonActorType extends CommonActorType {
    type: 'person'
    id: string
    name?: string
    // distinct_ids and is_identified are required for resolved persons but absent on
    // stubs returned when the ClickHouse actor_id couldn't be hydrated from Postgres
    // (see is_unresolved). Callers must guard for the stub case.
    distinct_ids?: string[]
    is_identified?: boolean
    // Set when the person's actor_id from ClickHouse couldn't be hydrated from Postgres
    // (typically because the person was merged into another or deleted). When true,
    // distinct_ids/is_identified/properties/created_at may all be missing.
    is_unresolved?: boolean
}

export interface GroupActorType extends CommonActorType {
    type: 'group'
    /** Group key. */
    id: string
    group_key: string
    group_type_index: integer
}

export interface SessionActorType extends CommonActorType {
    type: 'session'
    /** Session ID. */
    id: string
    person?: PersonActorType
}

export type ActorType = PersonActorType | GroupActorType | SessionActorType

export interface CohortGroupType {
    id: string
    days?: string
    action_id?: number
    event_id?: string
    label?: string
    count?: number
    count_operator?: string
    properties?: AnyPropertyFilter[]
    matchType: MatchType
    name?: string
}

// Synced with `posthog/models/property/property.py`
export interface CohortCriteriaType {
    id: string // Criteria filter id
    key: string
    value: BehavioralFilterType
    type: BehavioralFilterKey
    operator?: PropertyOperator | null
    group_type_index?: integer | null
    event_type?: TaxonomicFilterGroupType | null
    operator_value?: PropertyFilterValue
    time_value?: number | string | null
    time_interval?: TimeUnitType | null
    explicit_datetime?: string | null
    explicit_datetime_to?: string | null
    total_periods?: number | null
    min_periods?: number | null
    seq_event_type?: TaxonomicFilterGroupType | null
    seq_event?: string | number | null
    seq_time_value?: number | string | null
    seq_time_interval?: TimeUnitType | null
    negation?: boolean
    value_property?: PropertyFilterValue // Transformed into 'value' for api calls
    event_filters?: AnyPropertyFilter[] | null
    sort_key?: string // Client-side only stable id for sorting.
}

export type EmptyCohortGroupType = Partial<CohortGroupType>

export type EmptyCohortCriteriaType = Partial<CohortCriteriaType>

export type AnyCohortGroupType = CohortGroupType | EmptyCohortGroupType

export type AnyCohortCriteriaType = CohortCriteriaType | EmptyCohortCriteriaType

export type MatchType = typeof ENTITY_MATCH_TYPE | typeof PROPERTY_MATCH_TYPE

export interface CohortType {
    count?: number
    description?: string
    created_by?: UserBasicType | null
    created_at?: string
    deleted?: boolean
    id: number | 'new'
    version?: number | null
    pending_version?: number | null
    is_calculating?: boolean
    errors_calculating?: number
    last_calculation?: string
    last_error_message?: string | null
    /** Number of IDs supplied by the most recent static cohort import. */
    last_import_total_count?: number | null
    /** How many of those IDs matched no person, and so were left out of the cohort. */
    last_import_unmatched_count?: number | null
    is_static?: boolean
    name?: string
    csv?: File
    groups: CohortGroupType[] // To be deprecated once `filter` takes over
    filters: {
        properties: CohortCriteriaGroupFilter
        /** Exclude internal and test users (person-scoped team filters) at calculation time */
        filterTestAccounts?: boolean
    }
    experiment_set?: number[]
    /** Whether feature flags can target this cohort, and the progress of the history build that
     * gets it there. Null on projects the realtime pipeline does not cover. */
    realtime?: CohortRealtimeReadinessApi | null
    _create_in_folder?: string | null
    _create_static_person_ids?: string[]
}

export interface InsightHistory {
    id: number
    filters: Record<string, any>
    name?: string
    createdAt: string
    saved: boolean
    type: InsightType
}

export interface SavedFunnel extends InsightHistory {
    created_by: string
}

export type BinCountValue = number | typeof BIN_COUNT_AUTO

// https://github.com/PostHog/posthog/blob/master/posthog/constants.py#L106
export enum StepOrderValue {
    STRICT = 'strict',
    UNORDERED = 'unordered',
    ORDERED = 'ordered',
}

export enum PersonsTabType {
    PROFILE = 'profile',
    EVENTS = 'events',
    EXCEPTIONS = 'exceptions',
    SURVEY_RESPONSES = 'surveyResponses',
    SESSION_RECORDINGS = 'sessionRecordings',
    LOGS = 'logs',
    PROPERTIES = 'properties',
    COHORTS = 'cohorts',
    RELATED = 'related',
    HISTORY = 'history',
    FEATURE_FLAGS = 'featureFlags',
    EMAILS = 'emails',
    PUSH_NOTIFICATIONS = 'pushNotifications',
}

export enum GroupsTabType {
    PROFILE = 'profile',
    NOTES = 'notes',
    OVERVIEW = 'overview',
}

export interface EventsTableAction {
    name: string
    id: string
}

export interface EventsTableRowItem {
    event?: EventType
    date_break?: string
    new_events?: boolean
}

export interface EventType {
    // fields from the API
    id: string
    distinct_id: string
    properties: Record<string, any>
    event: string
    timestamp: string
    person?: Pick<PersonType, 'is_identified' | 'distinct_ids' | 'properties'>
    elements: ElementType[]
    elements_chain?: string | null
    uuid?: string
    person_id?: string
    person_mode?: string
}

export interface LiveEvent {
    uuid: string
    event: string
    properties: Record<string, any>
    timestamp: string
    team_id: number
    distinct_id: string
    created_at: string
}

export interface RecordingTimeMixinType {
    playerTime: number | null
}

export interface RecordingEventType
    extends Pick<EventType, 'id' | 'event' | 'properties' | 'timestamp' | 'elements'>, RecordingTimeMixinType {
    fullyLoaded: boolean
    // allowing for absent distinct id which events don't
    distinct_id?: EventType['distinct_id']
}

export interface SessionEventType extends Pick<EventType, 'id' | 'event' | 'properties' | 'timestamp'> {
    fullyLoaded: boolean
    distinct_id?: EventType['distinct_id']
}
export interface PlaylistCollectionCount {
    count: number
    watched_count: number
}

export interface PlaylistSavedFiltersCount {
    count: number
    watched_count: number
    has_more?: boolean
    increased?: boolean
    last_refreshed_at?: string
}

export interface PlaylistRecordingsCounts {
    saved_filters?: PlaylistSavedFiltersCount
    collection: PlaylistCollectionCount
}

export interface SessionRecordingPlaylistType {
    /** The primary key in the database, used as well in API endpoints */
    id: number
    short_id: string
    name: string
    derived_name?: string | null
    description?: string
    pinned?: boolean
    deleted: boolean
    created_at: string
    created_by: UserBasicType | null
    last_modified_at: string
    last_modified_by: UserBasicType | null
    filters?: LegacyRecordingFilters
    /**
     * the count of recordings matching filters, calculated periodically
     * and pinned recordings which is calculated in real-time
     * marked as has more if the filters count onoy matched one page and there are more available
     */
    recordings_counts?: PlaylistRecordingsCounts
    type: 'filters' | 'collection'
    /** Whether this playlist is a synthetic (virtual) playlist that's computed on-demand */
    is_synthetic?: boolean
    _create_in_folder?: string | null
    /** Write-only. */
    creation_method?: 'new' | 'pin' | 'duplicate'
}

export interface SavedSessionRecordingPlaylistsFilters {
    order: string
    search: string
    createdBy: number | 'All users'
    dateFrom: string | dayjs.Dayjs | undefined | null
    dateTo: string | dayjs.Dayjs | undefined | null
    page: number
    pinned: boolean
    type?: 'collection' | 'saved_filters'
}

export interface SavedSessionRecordingPlaylistsResult extends PaginatedResponse<SessionRecordingPlaylistType> {
    count: number
    /** not in the API response */
    filters?: SavedSessionRecordingPlaylistsFilters | null
}

export interface SessionRecordingSegmentType {
    start_time: string
    end_time: string
    window_id: string
    is_active: boolean
}

export interface SessionRecordingExternalReference {
    id: string
    integration: {
        id: number
        kind: IntegrationKind
        display_name: string
    }
    external_url: string
    title: string
    issue_id: string
    metadata?: Record<string, string>
}

export interface SessionRecordingType {
    id: string
    /** Whether this recording has been viewed by you already. */
    viewed: boolean
    /** user ids of other users who have viewed this recording */
    viewers: string[]
    /** Length of recording in seconds. */
    recording_duration: number
    active_seconds?: number
    inactive_seconds?: number
    /** When the recording starts in ISO format. */
    start_time: string
    /** When the recording ends in ISO format. */
    end_time: string
    /** List of matching events. **/
    matching_events?: MatchedRecording[]
    distinct_id?: string
    email?: string
    person?: PersonType
    click_count?: number
    keypress_count?: number
    /** count of all mouse activity in the recording, not just clicks */
    mouse_activity_count?: number
    start_url?: string
    console_log_count?: number
    console_warn_count?: number
    console_error_count?: number
    summary?: string
    snapshot_source: 'web' | 'mobile' | 'unknown'
    snapshot_library?: string
    /** whether we have received data for this recording in the last 5 minutes
     * (assumes the recording was loaded from ClickHouse)
     * **/
    ongoing?: boolean
    /**
     * calculated on the backend so that we can sort by it, definition may change over time
     */
    activity_score?: number
    /** retention period for this recording */
    retention_period_days?: number
    /** When the recording expires, in ISO format. */
    expiry_time?: string
    /** Number of whole days left until the recording expires. */
    recording_ttl?: number
    /** External references to third party issues. */
    external_references?: SessionRecordingExternalReference[]
    /** False when the recording was included in list results via a direct link despite not matching the filters. */
    matches_filters?: boolean
    /** Total stored size of the recording's snapshot data in bytes. Only present once metadata is loaded. */
    total_size?: number | null
    /** Number of captured rrweb events in the recording. Only present once metadata is loaded. */
    event_count?: number | null
}

export interface SessionRecordingUpdateType {
    viewed?: boolean
    analyzed?: boolean
    player_metadata?: Record<string, any> | null
    durations?: Record<string, any> | null
    $pathname: string
}

export interface SessionRecordingPropertiesType {
    id: string
    properties?: Record<string, any>
}

export interface PerformancePageView {
    session_id: string
    pageview_id: string
    timestamp: string
}
export interface RecentPerformancePageView extends PerformancePageView {
    page_url: string
    duration: number
}

// copied from rrweb/network@1
export type Body =
    | string
    | Document
    | Blob
    | ArrayBufferView
    | ArrayBuffer
    | FormData
    | URLSearchParams
    | ReadableStream<Uint8Array>
    | null

/**
 * This is our base type for tracking network requests.
 * It sticks relatively closely to the spec for the web
 * see https://developer.mozilla.org/en-US/docs/Web/API/Performance_API
 * we have renamed/added a few fields for the benefit of ClickHouse
 * but don't yet clash with the spec
 */
export interface PerformanceEvent {
    uuid: string
    timestamp: string | number
    distinct_id: string
    session_id: string
    window_id: string
    pageview_id: string
    current_url: string

    // BASE_EVENT_COLUMNS
    time_origin?: string
    entry_type?: string
    name?: string

    // RESOURCE_EVENT_COLUMNS
    start_time?: number
    duration?: number
    redirect_start?: number
    redirect_end?: number
    worker_start?: number
    fetch_start?: number
    domain_lookup_start?: number
    domain_lookup_end?: number
    connect_start?: number
    secure_connection_start?: number
    connect_end?: number
    request_start?: number
    response_start?: number
    response_end?: number
    decoded_body_size?: number
    encoded_body_size?: number

    initiator_type?:
        | 'navigation'
        | 'css'
        | 'script'
        | 'xmlhttprequest'
        | 'fetch'
        | 'beacon'
        | 'video'
        | 'audio'
        | 'track'
        | 'img'
        | 'image'
        | 'input'
        | 'a'
        | 'iframe'
        | 'frame'
        | 'link'
        | 'other'
    next_hop_protocol?: string
    render_blocking_status?: string
    response_status?: number
    // see https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/transferSize
    // zero has meaning for this field so should not be used unless the transfer size was known to be zero
    transfer_size?: number

    // LARGEST_CONTENTFUL_PAINT_EVENT_COLUMNS
    largest_contentful_paint_element?: string
    largest_contentful_paint_render_time?: number
    largest_contentful_paint_load_time?: number
    largest_contentful_paint_size?: number
    largest_contentful_paint_id?: string
    largest_contentful_paint_url?: string

    // NAVIGATION_EVENT_COLUMNS
    dom_complete?: number
    dom_content_loaded_event?: number
    dom_interactive?: number
    load_event_end?: number
    load_event_start?: number
    redirect_count?: number
    navigation_type?: string
    unload_event_end?: number
    unload_event_start?: number

    // Performance summary fields calculated on frontend
    first_contentful_paint?: number // https://web.dev/fcp/
    time_to_interactive?: number // https://web.dev/tti/
    total_blocking_time?: number // https://web.dev/tbt/
    web_vitals?: Set<RecordingEventType>

    // request/response capture - merged in from rrweb/network@1 payloads
    request_headers?: Record<string, string>
    response_headers?: Record<string, string>
    request_body?: Body
    response_body?: Body
    method?: string
    // normally, can rely on performance event values like duration,
    // but they may be absent in which case the SDK may have sent start and end time
    end_time?: number

    //rrweb/network@1 - i.e. not in ClickHouse table
    is_initial?: boolean
    raw?: Record<string, any>

    //server timings - reported as separate events but added back in here on the front end
    server_timings?: PerformanceEvent[]
}

export type AssetType = 'CSS' | 'JS' | 'Fetch' | 'Image' | 'Link' | 'XHR' | 'HTML'

export interface CurrentBillCycleType {
    current_period_start: number
    current_period_end: number
}

export type BillingFeatureType = {
    key: AvailableFeatureUnion
    name: string
    description?: string | null
    category?: string | null
    docsUrl?: string | null
    limit?: number | null
    note?: string | null
    unit?: string | null
    images?: {
        light: string
        dark: string
    } | null
    icon_key?: string | null
    entitlement_only?: boolean
    is_plan_default?: boolean
    type?: 'primary' | 'secondary' | null
}

export interface BillingTierType {
    flat_amount_usd: string
    unit_amount_usd: string
    current_amount_usd: string | null
    current_usage: number
    projected_usage: number | null
    projected_amount_usd: string | null
    up_to: number | null
}

export interface BillingTrialType {
    length: number
}

export interface BillingProductV2Type {
    type: string
    usage_key: string | null
    name: string
    headline: string | null
    description: string
    price_description?: string | null
    icon_key?: string | null
    image_url?: string | null
    screenshot_url: string | null
    docs_url: string
    free_allocation?: number | null
    subscribed: boolean | null
    tiers?: BillingTierType[] | null
    tiered: boolean
    current_usage?: number
    projected_amount_usd?: string | null
    projected_amount_usd_with_limit?: string | null
    projected_usage?: number
    percentage_usage: number
    current_amount_usd_before_addons: string | null
    current_amount_usd: string | null
    usage_limit: number | null
    has_exceeded_limit: boolean
    unit: string | null
    // Display formatting fields - for human-friendly display of usage values
    display_unit: string | null // Display unit (e.g., "GB" when internal unit is "MB")
    display_decimals: number | null // Decimal places in display (e.g., 2 for "27.65 GB")
    display_divisor: number | null // Divide raw value by this for display (e.g., 1000 for MB->GB)
    unit_amount_usd: string | null
    plans: BillingPlanType[]
    contact_support: boolean | null
    inclusion_only: any
    features: BillingFeatureType[]
    addons: BillingProductV2AddonType[]
    // addons-only: if this addon is included with the base product and not subscribed individually. for backwards compatibility.
    included_with_main_product?: boolean
    trial?: BillingTrialType | null
    legacy_product?: boolean | null
    // Billing refuses a customer billing limit for this product and returns no limit for it.
    no_billing_limit?: boolean
    // Set on a companion product: the type of the product whose card it is billed under.
    companion_of?: string | null
}

export interface BillingProductV2AddonType {
    name: string
    description: string
    price_description: string | null
    image_url: string | null
    icon_key?: string
    docs_url: string | null
    type: string
    tiers: BillingTierType[] | null
    tiered: boolean
    subscribed: boolean
    // sometimes addons are included with the base product, but they aren't subscribed individually
    included_with_main_product?: boolean
    inclusion_only: boolean | null
    contact_support: boolean | null
    unit: string | null
    // Display formatting fields - for human-friendly display of usage values
    display_unit: string | null // Display unit (e.g., "GB" when internal unit is "MB")
    display_decimals: number | null // Decimal places in display (e.g., 2 for "27.65 GB")
    display_divisor: number | null // Divide raw value by this for display (e.g., 1000 for MB->GB)
    unit_amount_usd: string | null
    default_unit_amount_usd?: string | null // Product's default (undiscounted) unit price
    current_amount_usd: string | null
    current_usage: number
    projected_usage: number | null
    projected_amount_usd: string | null
    plans: BillingPlanType[]
    usage_key?: string
    free_allocation?: number | null
    percentage_usage?: number
    features: BillingFeatureType[]
    included_if?:
        | 'no_active_subscription'
        | 'has_subscription'
        | 'no_active_parent_subscription'
        | 'has_parent_subscription'
        | null
    usage_limit?: number | null
    trial?: BillingTrialType | null
    legacy_product?: boolean | null
}
export enum BillingProvider {
    PostHog = 'posthog',
    Vercel = 'vercel',
}
export interface BillingType {
    customer_id: string
    has_active_subscription: boolean
    subscription_level: 'free' | 'paid' | 'custom'
    billing_provider?: BillingProvider | null
    free_trial_until?: Dayjs
    stripe_portal_url?: string
    external_billing_provider_invoices_url?: string
    current_total_amount_usd?: string
    current_total_amount_usd_after_discount?: string
    projected_total_amount_usd?: string
    projected_total_amount_usd_after_discount?: string
    projected_total_amount_usd_with_limit?: string
    projected_total_amount_usd_with_limit_after_discount?: string
    products: BillingProductV2Type[]
    usage_summary?: Record<
        string,
        {
            usage?: number | null
            limit?: number | null
            todays_usage?: number | null
            billing_start_date?: string
        }
    >

    custom_limits_usd?: {
        [key: string]: number | null
    }
    next_period_custom_limits_usd?: {
        [key: string]: number | null
    }
    billing_period?: {
        current_period_start: Dayjs
        current_period_end: Dayjs
        interval: 'month' | 'year'
    }
    license?: {
        plan: LicensePlan
    }
    available_plans?: BillingPlanType[]
    discount_percent?: number
    discount_amount_usd?: string
    amount_off_expires_at?: Dayjs
    trial?: {
        type: 'autosubscribe' | 'standard'
        status: 'active' | 'expired' | 'cancelled' | 'converted'
        target: 'paid' | 'teams' | 'enterprise' | 'boost' | 'scale'
        expires_at: string
    }
    billing_plan: BillingPlan | null
    startup_program_label?: StartupProgramLabel | null
    startup_program_label_previous?: StartupProgramLabel | null
    /** False when the YC credits do not renew, for example after a YC program block */
    startup_program_credits_renew?: boolean
    is_annual_plan_customer?: boolean | null
    account_owner?: {
        email?: string
        name?: string
    }
    billing_managed_by_partner?: { partner_name: string } | null
}

export interface ClaimedCouponInfo {
    code: string
    campaign_name: string
    campaign_slug: string | null
    claimed_at: string
    expires_at: string | null
    status: 'claimed' | 'expired'
}

export interface CouponsOverview {
    claimed_coupons: ClaimedCouponInfo[]
}

export interface BillingPeriod {
    start: Dayjs | null
    end: Dayjs | null
    interval: 'month' | 'year' | null
}

export interface BillingPlanType {
    free_allocation?: number | null
    features: BillingFeatureType[]
    name: string
    description: string
    is_free?: boolean
    plan_key?: string
    image_url: string | null
    docs_url: string | null
    note: string | null
    unit: string | null
    flat_rate: boolean
    product_key: `${ProductKey}`
    current_plan?: boolean | null
    tiers?: BillingTierType[] | null
    unit_amount_usd: string | null
    included_if?:
        | 'no_active_subscription'
        | 'has_subscription'
        | 'no_active_parent_subscription'
        | 'has_parent_subscription'
        | null
    initial_billing_limit?: number | null
    contact_support: boolean | null
}

export interface PlanInterface {
    key: string
    name: string
    custom_setup_billing_message: string
    image_url: string
    self_serve: boolean
    is_metered_billing: boolean
    event_allowance: number
    price_string: string
}

// Creating a nominal type: https://github.com/microsoft/TypeScript/issues/202#issuecomment-961853101
export type InsightShortId = string & { readonly '': unique symbol }

export enum InsightColor {
    White = 'white',
    Black = 'black',
    Blue = 'blue',
    Green = 'green',
    Purple = 'purple',
}

export interface Cacheable {
    last_refresh: string | null
    next_allowed_client_refresh?: string | null
    cache_target_age?: string | null
}

export interface TileLayout extends Omit<LayoutItem, 'i'> {
    i?: string // we use `i` in the front end but not in the API
}

export interface Tileable {
    layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never> // allow an empty object or one with DashboardLayoutSize keys
    color: InsightColor | null
}

export type DashboardTileIdOrNew = number | null

/** A tile before the API creates it, so it has no id or server-set fields yet. */
export type NewDashboardTile = Omit<Partial<DashboardTile>, 'text'> & {
    text?: Partial<NonNullable<DashboardTile['text']>>
}

export interface DashboardTile extends Tileable {
    id: number
    insight?: InsightModel
    text?: TextModel
    button_tile?: ButtonTileModel
    widget?: DashboardWidgetModel
    deleted?: boolean
    is_cached?: boolean
    order?: number
    error?: {
        type: string
        message: string
    }
    filters_overrides?: TileFilters
    show_description?: boolean | null
    transparent_background?: boolean | null
    group_key?: string | null
    badge?: TileBadge | null
}

export type TileBadge = 'winner' | 'cheeky-hog'

export type DashboardWidgetType = 'insight' | 'text' | 'button_tile' | 'widget'

export interface DashboardWidgetModel {
    id: string
    widget_type: string
    name?: string | null
    description?: string
    config: Record<string, unknown>
    created_by?: UserBasicType
    last_modified_by?: UserBasicType
    last_modified_at?: string
    team?: number
    dashboard_tiles?: DashboardTileBasicType[] | null
}

export interface DashboardTileBasicType {
    id: number
    dashboard_id: number
    deleted?: boolean
}

/** Shared fields for simple dashboard content models (text card, button tile, etc.). */
export interface DashboardWidgetInterface {
    id?: number
    /** Placements on dashboards (same shape as insight `dashboard_tiles`; preferred over legacy `dashboards` on insights where applicable). */
    dashboard_tiles?: DashboardTileBasicType[] | null
    created_by?: UserBasicType
    last_modified_by?: UserBasicType
    last_modified_at?: string
}

export interface TextModel extends DashboardWidgetInterface {
    body: string
    agent_context?: string | null
    last_modified_at: string
}

export interface ButtonTileModel extends DashboardWidgetInterface {
    url: string
    text: string
    placement: 'left' | 'right'
    style: 'primary' | 'secondary'
    team?: number
}

export interface InsightModel<R extends Node<Record<string, any>> = Node<Record<string, any>>>
    extends Cacheable, WithAccessControl {
    /** The unique key we use when communicating with the user, e.g. in URLs */
    short_id: InsightShortId
    /** The primary key in the database, used as well in API endpoints */
    id: number
    name: string
    derived_name?: string | null
    description?: string
    favorited?: boolean
    order: number | null
    result: any
    /** Result column names, served alongside `result`. SQL insights draw from these. */
    columns?: string[] | null
    /** ClickHouse type of each entry in `columns`, as [name, type] pairs. */
    types?: string[][] | null
    deleted: boolean
    saved: boolean
    created_at: string
    created_by: UserBasicType | null
    is_sample: boolean
    /**
     * @deprecated Session responses omit it, so read membership with `liveDashboardIds(insight.dashboard_tiles)`.
     * The app never sends it: on an unsaved insight it holds the dashboards to place the saved insight on.
     */
    dashboards?: number[]
    dashboard_tiles: DashboardTileBasicType[] | null
    updated_at: string
    tags?: string[]
    last_modified_at: string
    last_modified_by: UserBasicType | null
    last_viewed_at?: string | null
    viewers?: UserBasicType[]
    view_count?: number
    timezone?: string | null
    /** Only used in the frontend to store the next breakdown url */
    next?: string
    /** Only used in the frontend to toggle showing Baseline in funnels or not */
    disable_baseline?: boolean
    alerts?: AlertType[]
    query: R | null
    query_status?: QueryStatus
    query_scan?: QueryScanSummary
    warnings?: AnalyticsQueryResponseBase['warnings'] | null
    is_cached?: boolean
    filter_override_context?: InsightFilterOverrideContextApi | null
    resolved_date_range?: ResolvedDateRangeResponse | null
    /** Only used when creating objects */
    _create_in_folder?: string | null
}

export type InsightFilterOverrideContext = InsightFilterOverrideContextApi

export interface EndpointType extends WithAccessControl {
    id: string
    name: string
    description: string
    derived_from_insight?: string | null
    query: HogQLQuery | EndpointQueryNode
    is_active: boolean
    endpoint_path: string
    created_at: string
    updated_at: string
    created_by: UserBasicType | null
    data_freshness_seconds: number
    is_materialized: boolean
    current_version: number
    current_version_id: string
    versions_count: number
    /** Purely local value to determine whether the query endpoint should be highlighted, e.g. as a fresh duplicate. */
    _highlight?: boolean
    /** Last execution time from ClickHouse query_log table */
    last_executed_at?: string
    materialization?: EndpointVersionMaterializationType
    columns?: { name: string; type: string }[]
    bucket_overrides?: Record<string, string> | null
    tags?: string[]
    /** Breakdown property names that may be omitted on /run. Defaults to [] — every breakdown variable is required. */
    optional_breakdown_properties?: string[]
}

/** Extends EndpointType with version-specific fields when fetching a specific version */
export interface EndpointVersionType extends EndpointType {
    version: number
    version_id: string
    endpoint_is_active: boolean
    version_created_at: string
    version_created_by: UserBasicType | null
}

export interface EndpointVersionMaterializationType {
    can_materialize: boolean
    reason?: string
    status?: string
    error?: string
    last_materialized_at?: string
    saved_query_id?: string
    sync_frequency?: DataModelingSyncInterval
}

export interface DashboardBasicType extends WithAccessControl {
    id: number
    name: string
    description: string
    pinned: boolean
    created_at: string
    created_by: UserBasicType | null
    last_accessed_at: string | null
    last_viewed_at?: string | null
    is_shared: boolean
    deleted: boolean
    creation_mode: 'default' | 'template' | 'duplicate' | 'unlisted'
    tags?: string[]
    /** Project-tree folder the dashboard is filed under, e.g. 'Unfiled/Dashboards'. Empty string is the project root; null means no file system entry. */
    folder?: string | null
    /** Null when the dashboard was never filed, which is the case that cannot be moved. */
    file_system_id?: string | null
    /** Unlike `folder`, keeps the dashboard's own name as the last segment, which a move needs to compute the destination. */
    file_system_path?: string | null
    /** Purely local value to determine whether the dashboard should be highlighted, e.g. as a fresh duplicate. */
    _highlight?: boolean
    /**
     * The last time the dashboard was refreshed.
     * Used to block the dashboard refresh button.
     */
    last_refresh?: string | null
}

export interface DashboardTemplateListParams {
    scope?: DashboardTemplateScope
    // matches on template name, description, and tags
    search?: string
    /** When set, sort (not searching). Omit for server default order. Ignored when `search` is set. */
    ordering?: 'template_name' | '-template_name' | 'created_at' | '-created_at'
    /** When true, only curated featured templates. When false, only non-featured. */
    is_featured?: boolean
}

export type DashboardTemplateScope = 'team' | 'global' | 'feature_flag' | 'organization'

export interface DashboardType extends DashboardBasicType {
    tiles: DashboardTile[]
    filters: DashboardFilter
    variables?: Record<string, HogQLVariable>
    persisted_filters?: DashboardFilter | null
    persisted_variables?: Record<string, HogQLVariable> | null
    breakdown_colors?: BreakdownColorConfig[]
    data_color_theme_id?: number | null
    quick_filter_ids?: string[] | null
    customization?: {
        tile_spacing?: DashboardTileSpacing
        layout_compaction?: 'vertical' | 'horizontal' | 'stable'
        group_display?: TileGroupDisplay
        groups?: Record<string, DashboardTileGroupApi>
    }
}

export type DashboardTileSpacing = 'tight' | 'condensed' | 'standard' | 'relaxed' | 'wide'

export type TileGroupDisplay = 'sections' | 'tabs'

export enum TemplateAvailabilityContext {
    GENERAL = 'general',
    ONBOARDING = 'onboarding',
}

/**
 * One row in `DashboardTemplate.tiles` / save-as-template JSON — matches `dashboardToSaveableTemplate` and backend seed templates,
 * not the live dashboard `DashboardTile` shape (nested `insight` / `text` / `id`).
 */
export type DashboardTemplateStoredInsightTile = {
    type: 'INSIGHT'
    name?: string
    description?: string
    /** Serialized HogQL / insight node tree from the API; often plain JSON with string `kind` literals, not only `Node`/`NodeKind`. */
    query?: Node | Record<string, unknown> | null
    layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
    color?: InsightColor | null
    transparent_background?: boolean | null
    group_key?: string | null
    filters?: Record<string, unknown>
}

export type DashboardTemplateStoredTextTile = {
    type: 'TEXT'
    body: string
    agent_context?: string | null
    layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
    color?: InsightColor | null
    transparent_background?: boolean | null
    group_key?: string | null
}

export type DashboardTemplateStoredButtonTile = {
    type: 'BUTTON'
    button_tile: {
        url: string
        text: string
        placement: 'left' | 'right'
        style: 'primary' | 'secondary'
    }
    layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
    color?: InsightColor | null
    transparent_background?: boolean | null
    group_key?: string | null
}

export type DashboardTemplateStoredWidgetTile = {
    type: 'WIDGET'
    widget_type: string
    config?: Record<string, unknown>
    layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
    color?: InsightColor | null
    transparent_background?: boolean | null
    group_key?: string | null
}

export type DashboardTemplateStoredTile =
    | DashboardTemplateStoredInsightTile
    | DashboardTemplateStoredTextTile
    | DashboardTemplateStoredButtonTile
    | DashboardTemplateStoredWidgetTile

/** Project-specific references embedded in a template's tiles that may not resolve in another project. */
export interface NonPortableReferences {
    actions: number
    cohorts: number
    warehouse_tables: string[]
}

export interface DashboardTemplateType {
    id: string
    team_id?: number
    created_at?: string
    created_by?: UserBasicType | null
    template_name: string
    dashboard_description?: string
    dashboard_filters?: DashboardFilter
    tiles: DashboardTemplateStoredTile[]
    variables?: DashboardTemplateVariableType[]
    customization?: DashboardType['customization'] | null
    tags?: string[]
    image_url?: string
    scope?: DashboardTemplateScope
    availability_contexts?: TemplateAvailabilityContext[]
    /** Manually curated highlight flag. */
    is_featured?: boolean
    /** Soft delete; API allows PATCH for staff undo (restore). */
    deleted?: boolean
    /** Read-only. Project-specific references in tiles (actions, cohorts, warehouse tables) that may not resolve in another project. */
    non_portable_references?: NonPortableReferences
}

export interface MonacoMarker {
    message: string
}

// makes the DashboardTemplateType properties optional; tiles stay API/wire JSON shape
export type DashboardTemplateEditorType = Partial<Omit<DashboardTemplateType, 'tiles'>> & {
    tiles: DashboardTemplateStoredTile[]
}

export interface DashboardTemplateVariableType {
    id: string
    name: string
    description: string
    type: 'event'
    default: TemplateVariableStep
    required: boolean
    touched?: boolean
    selector?: string
    href?: string
    url?: string
}

export type DashboardLayoutSize = 'sm' | 'xs'

export interface OrganizationInviteType {
    id: string
    target_email: string
    first_name: string
    level: OrganizationMembershipLevel
    is_expired: boolean
    emailing_attempt_made: boolean
    email_suppressed: boolean
    created_by: UserBasicType | null
    created_at: string
    updated_at: string
    message?: string
    private_project_access?: Array<{
        id: number
        level: AccessControlLevel.Member | AccessControlLevel.Admin
    }>
}

export enum PluginInstallationType {
    Local = 'local',
    Custom = 'custom',
    Repository = 'repository',
    Source = 'source',
    Inline = 'inline',
}

export interface PluginType {
    id: number
    plugin_type: PluginInstallationType
    name: string
    description?: string
    url?: string
    tag?: string
    icon?: string
    latest_tag?: string // apps management page: The latest git hash for the repo behind the url
    config_schema: Record<string, PluginConfigSchema> | PluginConfigSchema[]
    source?: string
    maintainer?: string
    is_global: boolean
    organization_id: string
    organization_name: string
    metrics?: Record<string, StoredMetricMathOperations>
    capabilities?: Record<'jobs' | 'methods' | 'scheduled_tasks', string[] | undefined>
    public_jobs?: Record<string, JobSpec>
    hog_function_migration_available?: boolean
}

export type AppType = PluginType

export interface JobPayloadFieldOptions {
    type: 'string' | 'boolean' | 'json' | 'number' | 'date' | 'daterange'
    title?: string
    required?: boolean
    default?: any
    staff_only?: boolean
}

export interface JobSpec {
    payload?: Record<string, JobPayloadFieldOptions>
}

/** @deprecated in favor of PluginConfigTypeNew */
export interface PluginConfigType {
    id?: number
    plugin: number
    team_id: number
    enabled: boolean
    order: number

    config: Record<string, any>
    error?: PluginErrorType
    created_at?: string
}

/** @deprecated in favor of PluginConfigWithPluginInfoNew */
export interface PluginConfigWithPluginInfo extends PluginConfigType {
    id: number
    plugin_info: PluginType
}

// TODO: Rename to PluginConfigType once the legacy PluginConfigType are removed from the frontend
export interface PluginConfigTypeNew {
    id: number
    plugin: number
    team_id: number
    enabled: boolean
    order: number
    name: string
    description?: string
    updated_at: string
    config: Record<string, any>
}

// TODO: Rename to PluginConfigWithPluginInfo once the are removed from the frontend
export interface PluginConfigWithPluginInfoNew extends PluginConfigTypeNew {
    plugin_info: PluginType
}

export interface PluginErrorType {
    message: string
    time: string
    stack?: string
    name?: string
    event?: Record<string, any>
}

export type LogEntryLevel = 'DEBUG' | 'LOG' | 'INFO' | 'WARN' | 'WARNING' | 'ERROR'

// The general log entry format that eventually everything should match
export type LogEntry = {
    log_source_id: string
    instance_id: string
    timestamp: string
    level: LogEntryLevel
    message: string
}

export type LogEntryRequestParams = {
    limit?: number
    after?: string
    before?: string
    // Comma separated list of log levels
    level?: string
    search?: string
    instance_id?: string
}

export interface PluginLogEntry {
    id: string
    team_id: number
    plugin_id: number
    plugin_config_id: number
    timestamp: string
    source: string
    type: LogEntryLevel
    is_system: boolean
    message: string
    instance_id: string
}

export enum AnnotationScope {
    Insight = 'dashboard_item',
    Dashboard = 'dashboard',
    Project = 'project',
    Organization = 'organization',
}

export interface RawAnnotationType {
    id: number
    scope: AnnotationScope
    content: string | null
    date_marker: string | null
    created_by?: UserBasicType | null
    created_at: string
    updated_at: string
    dashboard_item?: number | null
    insight_short_id?: InsightModel['short_id'] | null
    insight_name?: InsightModel['name'] | null
    insight_derived_name?: InsightModel['derived_name'] | null
    dashboard_id?: DashboardBasicType['id'] | null
    dashboard_name?: DashboardBasicType['name'] | null
    deleted?: boolean
    creation_type?: 'USR' | 'GIT'
    /** Optional emoji shown in place of the default badge when surfacing the annotation. */
    emoji?: string | null
    /** When true, the annotation is hidden from the UI but still readable over the API and MCP. */
    hidden_in_user_interface?: boolean | null
}

export interface AnnotationType extends Omit<RawAnnotationType, 'created_at' | 'date_marker'> {
    date_marker: dayjs.Dayjs | null
    created_at: dayjs.Dayjs
}

export interface DatedAnnotationType extends Omit<AnnotationType, 'date_marker'> {
    date_marker: dayjs.Dayjs
}

export enum ChartDisplayType {
    Auto = 'Auto',
    ActionsLineGraph = 'ActionsLineGraph',
    // TODO: remove this as ActionsBar was meant to be for unstacked bar charts
    // but with current logic for all insights with this setting saved in the query
    // we still show them stacked bars
    ActionsBar = 'ActionsBar',
    ActionsUnstackedBar = 'ActionsUnstackedBar',
    ActionsStackedBar = 'ActionsStackedBar',
    ActionsAreaGraph = 'ActionsAreaGraph',
    ActionsLineGraphCumulative = 'ActionsLineGraphCumulative',
    BoldNumber = 'BoldNumber',
    Metric = 'Metric',
    ActionsPie = 'ActionsPie',
    ActionsDonut = 'ActionsDonut',
    ActionsProportionBar = 'ActionsProportionBar',
    ActionsBarValue = 'ActionsBarValue',
    ActionsTable = 'ActionsTable',
    WorldMap = 'WorldMap',
    CalendarHeatmap = 'CalendarHeatmap',
    TwoDimensionalHeatmap = 'TwoDimensionalHeatmap',
    BoxPlot = 'BoxPlot',
    SlopeGraph = 'SlopeGraph',
    ScatterPlot = 'ScatterPlot',
}
export enum ChartDisplayCategory {
    TimeSeries = 'TimeSeries',
    CumulativeTimeSeries = 'CumulativeTimeSeries',
    TotalValue = 'TotalValue',
}

export type BreakdownType =
    | 'cohort'
    | 'person'
    | 'event'
    | 'event_metadata'
    | 'element'
    | 'group'
    | 'session'
    | 'hogql'
    | 'data_warehouse'
    | 'data_warehouse_person_property'
    | 'revenue_analytics'
export type IntervalType = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'
export type SimpleIntervalType = 'day' | 'month'
export type SmoothingType = number
export type InsightSceneSource = 'web-analytics' | 'llm-analytics' | 'endpoints'

export enum InsightType {
    TRENDS = 'TRENDS',
    STICKINESS = 'STICKINESS',
    LIFECYCLE = 'LIFECYCLE',
    FUNNELS = 'FUNNELS',
    RETENTION = 'RETENTION',
    PATHS = 'PATHS',
    JOURNEYS = 'JOURNEYS',
    JSON = 'JSON',
    SQL = 'SQL',
    HOG = 'HOG',
    WEB_ANALYTICS = 'WEB_ANALYTICS',
    METRICS = 'METRICS',
}

export enum PathType {
    PageView = '$pageview',
    Screen = '$screen',
    CustomEvent = 'custom_event',
    HogQL = 'hogql',
}

export enum FunnelPathType {
    before = 'funnel_path_before_step',
    between = 'funnel_path_between_steps',
    after = 'funnel_path_after_step',
}

export enum FunnelVizType {
    Steps = 'steps',
    TimeToConvert = 'time_to_convert',
    Trends = 'trends',
    Flow = 'flow',
}

export type RetentionType =
    | typeof RETENTION_RECURRING
    | typeof RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS
    | typeof RETENTION_FIRST_EVER_OCCURRENCE

export enum RetentionPeriod {
    Hour = 'Hour',
    Day = 'Day',
    Week = 'Week',
    Month = 'Month',
}

export type SlowQueryPossibilities = 'all_events' | 'large_date_range' | 'first_time_for_user' | 'strict_funnel'

export type BreakdownKeyType = integer | string | number | (integer | string | number)[] | null

/**
 * Legacy breakdown.
 */
export interface Breakdown {
    property: string | number
    type: BreakdownType
    normalize_url?: boolean
    histogram_bin_count?: number
    group_type_index?: number
}

export interface FilterType {
    // used by all
    from_dashboard?: boolean | number
    insight?: InsightType
    filter_test_accounts?: boolean
    properties?: AnyPropertyFilter[] | PropertyGroupFilter
    sampling_factor?: number | null

    date_from?: string | null
    date_to?: string | null
    /**
     * Whether the `date_from` and `date_to` should be used verbatim. Disables rounding to the start and end of period.
     * Strings are cast to bools, e.g. "true" -> true.
     */
    explicit_date?: boolean | string | null

    // used by trends and stickiness
    interval?: IntervalType
    // TODO: extract into TrendsFunnelsCommonFilterType
    breakdown_type?: BreakdownType | null
    breakdown?: BreakdownKeyType
    breakdown_normalize_url?: boolean
    breakdowns?: Breakdown[]
    breakdown_group_type_index?: integer | null
    breakdown_hide_other_aggregation?: boolean | null
    breakdown_limit?: integer | null
    aggregation_group_type_index?: integer // Groups aggregation
}

export interface TemplateVariableStep {
    id?: string
    math?: BaseMathType
    name?: string | null
    order?: number
    type?: EntityTypes
    event?: string
    selector?: string | null
    href?: string | null
    url?: string | null
    properties?: Record<string, any>[]
    custom_name?: string
    custom_event?: boolean
}

export interface TrendsFilterType extends FilterType {
    // Specifies that we want to smooth the aggregation over the specified
    // number of intervals, e.g. for a day interval, we may want to smooth over
    // 7 days to remove weekly variation. Smoothing is performed as a moving average.
    smoothing_intervals?: number
    formula?: string
    compare_to?: string
    compare?: boolean
    /** @deprecated */
    shown_as?: ShownAsValue
    display?: ChartDisplayType
    breakdown_histogram_bin_count?: number // trends breakdown histogram bin count

    // frontend only
    show_alert_threshold_lines?: boolean // used to show/hide horizontal lines on insight representing alert thresholds set on the insight
    show_legend?: boolean // used to show/hide legend next to insights graph
    hidden_legend_keys?: Record<string, boolean | undefined> // used to toggle visibilities in table and legend
    aggregation_axis_format?: AggregationAxisFormat // a fixed format like duration that needs calculation
    aggregation_axis_prefix?: string // a prefix to add to the aggregation axis e.g. £
    aggregation_axis_postfix?: string // a postfix to add to the aggregation axis e.g. %
    decimal_places?: number
    min_decimal_places?: number
    x_axis_label?: string
    y_axis_label?: string
    show_values_on_series?: boolean
    show_labels_on_series?: boolean
    show_percent_stack_view?: boolean
    y_axis_scale_type?: 'log10' | 'linear'
    show_multiple_y_axes?: boolean
}

export interface StickinessFilterType extends FilterType {
    compare_to?: string
    compare?: boolean
    /** @deprecated */
    shown_as?: ShownAsValue
    display?: ChartDisplayType

    // frontend only
    show_legend?: boolean // used to show/hide legend next to insights graph
    hidden_legend_keys?: Record<string, boolean | undefined> // used to toggle visibilities in table and legend
    show_values_on_series?: boolean
    show_multiple_y_axes?: boolean

    // persons only
    stickiness_days?: number
}

export interface FunnelsFilterType extends FilterType {
    funnel_viz_type?: FunnelVizType // parameter sent to funnels API for time conversion code path
    funnel_from_step?: number // used in time to convert: initial step index to compute time to convert
    funnel_to_step?: number // used in time to convert: ending step index to compute time to convert
    breakdown_attribution_type?: BreakdownAttributionType // funnels breakdown attribution type
    breakdown_attribution_value?: number // funnels breakdown attribution specific step value
    bin_count?: BinCountValue // used in time to convert: number of bins to show in histogram
    funnel_window_interval_unit?: FunnelConversionWindowTimeUnit // minutes, days, weeks, etc. for conversion window
    funnel_window_interval?: number | undefined // length of conversion window
    funnel_order_type?: StepOrderValue
    funnel_aggregate_by_hogql?: string | null

    // frontend only
    layout?: FunnelLayout // used only for funnels
    funnel_step_reference?: FunnelStepReference // whether conversion shown in graph should be across all steps or just from the previous step
    hidden_legend_keys?: Record<string, boolean | undefined> // used to toggle visibilities in table and legend

    // persons only
    entrance_period_start?: string // this and drop_off is used for funnels time conversion date for the persons modal
    drop_off?: boolean
    funnel_step?: number
    funnel_step_breakdown?: string | number[] | number | null // used in steps breakdown: persons modal
    funnel_custom_steps?: number[] // used to provide custom steps for which to get people in a funnel
}
export interface PathsFilterType extends FilterType {
    path_type?: PathType
    paths_hogql_expression?: string
    include_event_types?: PathType[]
    start_point?: string
    end_point?: string
    path_groupings?: string[]
    funnel_paths?: FunnelPathType
    exclude_events?: string[] // Paths Exclusion type
    /** @asType integer */
    step_limit?: number // Paths Step Limit
    path_replacements?: boolean
    local_path_cleaning_filters?: PathCleaningFilter[] | null
    /** @asType integer */
    edge_limit?: number | undefined // Paths edge limit
    /** @asType integer */
    min_edge_weight?: number | undefined // Paths
    /** @asType integer */
    max_edge_weight?: number | undefined // Paths

    // persons only
    path_start_key?: string // Paths People Start Key
    path_end_key?: string // Paths People End Key
    path_dropoff_key?: string // Paths People Dropoff Key
}

export type RetentionEntityKind = NodeKind.ActionsNode | NodeKind.EventsNode

export interface RetentionEntity {
    id?: string | number // TODO: Fix weird typing issues
    kind?: RetentionEntityKind
    name?: string
    type?: EntityType
    /**  @asType integer */
    order?: number
    uuid?: string
    custom_name?: string
    /** filters on the event */
    properties?: AnyPropertyFilter[]
    /** Data warehouse table name */
    table_name?: string
    /** Data warehouse timestamp field */
    timestamp_field?: string
    /** Data warehouse field used as the actor identifier */
    aggregation_target_field?: string
}

export enum RetentionDashboardDisplayType {
    TableOnly = 'table_only',
    GraphOnly = 'graph_only',
    All = 'all',
}

export interface RetentionFilterType extends FilterType {
    retention_type?: RetentionType
    /** Whether retention is with regard to initial cohort size, or that of the previous period. */
    retention_reference?: 'total' | 'previous'
    /**
     * @asType integer
     */
    total_intervals?: number
    period?: RetentionPeriod
    cumulative?: boolean

    //frontend only
    show_mean?: boolean // deprecated
    mean_retention_calculation?: 'simple' | 'weighted' | typeof RETENTION_MEAN_NONE
}
export interface LifecycleFilterType extends FilterType {
    /** @deprecated */
    shown_as?: ShownAsValue

    // frontend only
    show_legend?: boolean
    show_values_on_series?: boolean
    toggledLifecycles?: LifecycleToggle[]
}

export type LifecycleToggle = 'new' | 'resurrecting' | 'returning' | 'dormant'
export type AnyPartialFilterType =
    | Partial<TrendsFilterType>
    | Partial<StickinessFilterType>
    | Partial<FunnelsFilterType>
    | Partial<PathsFilterType>
    | Partial<RetentionFilterType>
    | Partial<LifecycleFilterType>
    | Partial<FilterType>

export interface EventsListQueryParams {
    event?: string
    properties?: AnyPropertyFilter[] | PropertyGroupFilter
    orderBy?: string[]
    action_id?: number
    after?: string
    before?: string
    limit?: number
    offset?: number
}

export interface RecordingEventsFilters {
    query: string
}

export interface RecordingConsoleLogsFilters {
    query: string
}

export enum RecordingWindowFilter {
    All = 'all',
}

export interface EditorFilterProps {
    insightProps: InsightLogicProps
}

export interface InsightEditorFilter {
    key: string
    label?: string | ((props: EditorFilterProps) => JSX.Element | null)
    tooltip?: JSX.Element
    showOptional?: boolean
    /** Editor filter component. Cannot be an anonymous function or the key would not work! */
    component?: (props: EditorFilterProps) => JSX.Element | null
}

export type InsightEditorFilterGroup = {
    title: string
    editorFilters: InsightEditorFilter[]
    defaultExpanded?: boolean
    show?: boolean
    /** Summary shown next to the title when the section is collapsed (e.g. "3 filters", "$browser, $os") */
    collapsedSummary?: string | null
    /** Extra content rendered in the tile header next to the title */
    headerExtra?: ReactNode
}

export interface SystemStatusSubrows {
    columns: string[]
    rows: string[][]
}

export interface SystemStatusRow {
    metric: string
    value: boolean | string | number | null
    key: string
    description?: string
    subrows?: SystemStatusSubrows
}

export interface SystemStatus {
    overview: SystemStatusRow[]
}

export type QuerySummary = { duration: string } & Record<string, string>

export interface SystemStatusQueriesResult {
    postgres_running: QuerySummary[]
    clickhouse_running?: QuerySummary[]
    clickhouse_slow_log?: QuerySummary[]
}

export interface SystemStatusAnalyzeResult {
    query: string
    timing: {
        query_id: string
        event_time: string
        query_duration_ms: number
        read_rows: number
        read_size: string
        result_rows: number
        result_size: string
        memory_usage: string
    }
    flamegraphs: Record<string, string>
}

export interface TrendAPIResponse<ResultType = TrendResult[]> {
    type: 'Trends'
    is_cached: boolean
    last_refresh: string | null
    result: ResultType
    timezone: string
    next: string | null
}

export interface TrendResult {
    count: number
    data: number[]
    days: string[]
    dates?: string[]
    label: string
    labels: string[]
    breakdown_value?: string | number | string[]
    aggregated_value: number
    status?: string
    compare_label?: CompareLabelType
    compare?: boolean
    persons_urls?: { url: string }[]
    persons?: Person
    /** Series order set by the query runner: the series index for plain series, or the
     * formula index for formula results (uniform across a formula's breakdown rows). */
    order?: number
    /** Slope graph only: whether the last bucket is the current, still-accumulating period. Set by
     * SlopeGraphTrendsQueryRunner so the insight and MCP dash the provisional end identically. */
    incomplete_end?: boolean
}

interface Person {
    url: string
    filter: Partial<FilterType>
}

export interface FunnelStep {
    // The type returned from the API.
    average_conversion_time: number | null
    median_conversion_time: number | null
    count: number
    name: string
    custom_name?: string | null
    order: number
    people?: string[]
    labels?: string[]
    breakdown?: BreakdownKeyType
    breakdowns?: BreakdownKeyType[]
    breakdown_value?: BreakdownKeyType
    data?: number[]
    days?: string[]

    /** Set by the funnel compare orchestrator to tag which period a step belongs to. */
    compare_label?: 'current' | 'previous'

    /** Url that you can GET to retrieve the people that converted in this step */
    converted_people_url: string

    /** Url that you can GET to retrieve the people that dropped in this step  */
    dropped_people_url: string | null
}

export interface FunnelsTimeConversionBins {
    bins: [number, number][]
    average_conversion_time: number | null
    median_conversion_time: number | null
}

export type FunnelResultType = FunnelStep[] | FunnelStep[][] | FunnelsTimeConversionBins

export interface FunnelAPIResponse<ResultType = FunnelResultType> {
    is_cached: boolean
    last_refresh: string | null
    result: ResultType
    timezone: string
}

export interface FunnelStepWithNestedBreakdown extends FunnelStep {
    nested_breakdown?: FunnelStep[]
}

export interface FunnelTimeConversionMetrics {
    /** Null when the result predates the median field (old cache) — the header hides the figure in that case. */
    medianTime: number | null
    stepRate: number
    totalRate: number
}

export interface FunnelConversionWindow {
    funnelWindowIntervalUnit: FunnelConversionWindowTimeUnit
    funnelWindowInterval?: number
}

export enum FunnelConversionWindowTimeUnit {
    Second = 'second',
    Minute = 'minute',
    Hour = 'hour',
    Day = 'day',
    Week = 'week',
    Month = 'month',
}

export enum FunnelStepReference {
    total = 'total',
    previous = 'previous',
}

export interface FunnelStepWithConversionMetrics extends FunnelStep {
    droppedOffFromPrevious: number
    conversionRates: {
        fromPrevious: number
        total: number
        fromBasisStep: number // either fromPrevious or total, depending on FunnelStepReference
    }
    nested_breakdown?: Omit<FunnelStepWithConversionMetrics, 'nested_breakdown'>[]
    rowKey?: number | string
    significant?: {
        fromPrevious: boolean
        total: boolean
        fromBasisStep: boolean // either fromPrevious or total, depending on FunnelStepReference
    }
}

export interface FlattenedFunnelStepByBreakdown {
    rowKey: number | string
    isBaseline?: boolean
    breakdown?: BreakdownKeyType
    // :KLUDGE: Data transforms done in `getBreakdownStepValues`
    breakdown_value?: Array<string | number>
    breakdownIndex?: number
    /** Compare period this row represents; both rows of a pair share breakdown_value and color. */
    compare_label?: 'current' | 'previous'
    /** Color position shared by both rows of a compare pair; falls back to breakdownIndex. */
    colorIndex?: number
    conversionRates?: {
        total: number
    }
    steps?: FunnelStepWithConversionMetrics[]
    significant?: boolean
}

export enum BreakdownAttributionType {
    FirstTouch = 'first_touch',
    LastTouch = 'last_touch',
    AllSteps = 'all_events',
    Step = 'step',
}

export interface ChartParams {
    inCardView?: boolean
    inSharedMode?: boolean
    showPersonsModal?: boolean
    /** allows overriding by queries, e.g. setting empty state text*/
    context?: QueryContext<InsightVizNode>
}

export interface HistogramGraphDatum {
    id: number
    bin0: number
    bin1: number
    count: number
    label: string
}

// Shared between insightLogic, dashboardItemLogic, trendsLogic, funnelLogic, pathsLogic, retentionLogic
export interface InsightLogicProps<Q extends QuerySchema = QuerySchema> {
    /** currently persisted insight */
    dashboardItemId?: InsightShortId | 'new' | `new-${string}` | null
    /** id of the dashboard the insight is on (when the insight is being displayed on a dashboard) **/
    dashboardId?: DashboardType['id']
    /** render a static picture of the insight, hiding interactive controls such as filter bars (e.g. in exports) */
    presentationOnly?: boolean
    /** cached insight */
    cachedInsight?: Partial<InsightModel> | null
    /** Reuse recent completed responses when this embedded insight remounts. */
    retainResponseOnUnmount?: boolean
    /** enable this to avoid API requests */
    doNotLoad?: boolean
    loadPriority?: number
    onData?: (data: Record<string, unknown> | null | undefined) => void
    /** query when used as ad-hoc insight */
    query?: Q
    setQuery?: (node: Q) => void
    refreshAfterDisplayOptionsChange?: (insight: InsightModel) => void

    /** Used to group DataNodes into a collection for group operations like refreshAll **/
    dataNodeCollectionId?: string

    /** Dashboard filters to override the ones in the query */
    filtersOverride?: DashboardFilter | null
    /** Dashboard variables to override the ones in the query */
    variablesOverride?: Record<string, HogQLVariable> | null
    /** Tile filters to override the ones in the query */
    tileFiltersOverride?: TileFilters | null
    /** The tab of the scene if the insight is a full scene insight */
    tabId?: string | null
    /**
     * The project the insight comes from, when a page shows insights from several projects. Its
     * charts then show that project's annotations, read-only, in that project's time zone.
     */
    sourceProject?: InsightSourceProject
}

export interface InsightSourceProject {
    id: number
    /** Unknown until the page has loaded the project, and the chart uses the current project's time zone until then. */
    timezone?: string
}

export interface SetInsightOptions {
    /** this overrides the in-flight filters on the page, which may not equal the last returned API response */
    overrideQuery?: boolean
    /** calling with this updates the "last saved" filters */
    fromPersistentApi?: boolean
}

export enum SurveySchedule {
    Once = 'once',
    Recurring = 'recurring',
    Always = 'always',
}

export enum SurveyPartialResponses {
    Yes = 'true',
    No = 'false',
}

export interface SurveyEventsWithProperties {
    name: string
    propertyFilters?: {
        [propertyName: string]: {
            values: string[]
            operator: PropertyMatchType
        }
    }
}

export interface SurveyDisplayConditions {
    url?: string
    selector?: string
    seenSurveyWaitPeriodInDays?: number
    urlMatchType?: SurveyMatchType
    deviceTypes?: string[]
    deviceTypesMatchType?: SurveyMatchType
    linkedFlagVariant?: string
    actions: {
        values: {
            id: number
            name: string
        }[]
    } | null
    /** events that trigger surveys */
    events: {
        repeatedActivation?: boolean
        values: SurveyEventsWithProperties[]
    } | null
    /** events that cancel "pending" (time-delayed) surveys */
    cancelEvents?: {
        values: SurveyEventsWithProperties[]
    } | null
}

export enum SurveyEventName {
    SHOWN = 'survey shown',
    DISMISSED = 'survey dismissed',
    ABANDONED = 'survey abandoned',
    SENT = 'survey sent',
}

export enum SurveyEventProperties {
    SURVEY_ID = '$survey_id',
    SURVEY_RESPONSE = '$survey_response',
    SURVEY_ITERATION = '$survey_iteration',
    SURVEY_PARTIALLY_COMPLETED = '$survey_partially_completed',
    SURVEY_SUBMISSION_ID = '$survey_submission_id',
    SURVEY_COMPLETED = '$survey_completed',
}

export interface SurveyEventStats {
    total_count: number
    total_count_only_seen: number
    unique_persons: number
    unique_persons_only_seen: number
    first_seen: string | null
    last_seen: string | null
}

export interface SurveyRates {
    response_rate: number
    dismissal_rate: number
    unique_users_response_rate: number
    unique_users_dismissal_rate: number
}

export interface SurveyStats {
    [SurveyEventName.SHOWN]: SurveyEventStats
    [SurveyEventName.DISMISSED]: SurveyEventStats
    [SurveyEventName.SENT]: SurveyEventStats
}
export interface SurveyStatsResponse {
    stats: SurveyStats
    rates: SurveyRates
}

export interface ChoiceQuestionResponseData {
    label: string
    value: number
    isPredefined: boolean
    // For unique responses (value === 1), include person data for display
    distinctId?: string
    /** Pre-computed display name from server (email, name, etc.) - avoids brittle client-side property extraction */
    personDisplayName?: string
    timestamp?: string
}

export interface OpenQuestionResponseData {
    distinctId: string
    response: string
    /** Pre-computed display name from server (email, name, etc.) - avoids brittle client-side property extraction */
    personDisplayName?: string
    timestamp?: string
    sessionId?: string
}

export interface ChoiceQuestionProcessedResponses {
    type: SurveyQuestionType.SingleChoice | SurveyQuestionType.Rating | SurveyQuestionType.MultipleChoice
    data: ChoiceQuestionResponseData[]
    totalResponses: number
    noResponseCount: number
}

export interface OpenQuestionProcessedResponses {
    type: SurveyQuestionType.Open
    data: OpenQuestionResponseData[]
    totalResponses: number
}

export type QuestionProcessedResponses = ChoiceQuestionProcessedResponses | OpenQuestionProcessedResponses

export interface ResponsesByQuestion {
    [questionId: string]: QuestionProcessedResponses
}

export interface ConsolidatedSurveyResults {
    responsesByQuestion: {
        [questionId: string]: QuestionProcessedResponses
    }
}

/**
 * Raw survey response data from the SQL query.
 * Each SurveyResponseRow represents one user's complete response to all questions.
 *
 * Structure:
 * - response[questionIndex] contains the answer to that specific question
 * - For rating/single choice/open questions: response[questionIndex] is a string
 * - For multiple choice questions: response[questionIndex] is a string[]
 * - The last elements may contain metadata like person properties and distinct_id
 *
 * Example:
 * [
 *   ["9", ["Customer case studies"], "Great product!", "user123"],
 *   ["7", ["Tutorials", "Other"], "Good but could improve", "user456"]
 * ]
 */
export type SurveyResponseRow = Array<null | string | string[]>
export type SurveyRawResults = SurveyResponseRow[]

// Product Tours
export type ProductTourSurveyQuestionType = 'open' | 'rating'

export interface ProductTourSurveyQuestion {
    type: ProductTourSurveyQuestionType
    questionText: string
    /** Rating display type - emoji or number */
    display?: 'emoji' | 'number'
    /** Rating scale - 3 or 5 for emoji, 5 or 10 for number */
    scale?: 3 | 5 | 10
    /** Label for low end of rating scale (e.g., "Not likely") */
    lowerBoundLabel?: string
    /** Label for high end of rating scale (e.g., "Very likely") */
    upperBoundLabel?: string
    submitButtonText?: string
    backButtonText?: string
}

export type ProductTourProgressionTriggerType = 'button' | 'click'

// 'element' is deprecated in favor of all 'modal' steps having the option
// to be positioned near a given element.
export type ProductTourStepType = 'element' | 'modal' | 'survey' | 'banner'

export interface ProductTourBannerConfig {
    /**
     * sticky: injected at top of body, fixed pos, stays visible on scroll
     * static: injected at top of body, fixed pos, scrolls away with page
     * custom: injected into a container from user-supplied css selector
     */
    behavior: 'sticky' | 'static' | 'custom'
    selector?: string
    action?: {
        type: 'none' | 'link' | 'trigger_tour'
        link?: string
        tourId?: string
    }
    animation?: {
        duration: number
    }
}

export type ProductTourButtonAction = 'dismiss' | 'link' | 'next_step' | 'previous_step' | 'trigger_tour'

export interface ProductTourStepButton {
    text: string
    action: ProductTourButtonAction
    /** URL to open when action is 'link' */
    link?: string
    /** Tour ID to trigger when action is 'trigger_tour' */
    tourId?: string
}

export interface ProductTourStepButtons {
    primary?: ProductTourStepButton
    secondary?: ProductTourStepButton
}

/** Preset width options for product tour tooltips */
export type ProductTourStepWidth = 'compact' | 'default' | 'wide' | 'extra-wide'

/** Width values in pixels for each preset */
export const PRODUCT_TOUR_STEP_WIDTHS: Record<ProductTourStepWidth, number> = {
    compact: 280,
    default: 360,
    wide: 480,
    'extra-wide': 700,
}

export type ProductTourStepTargeting = 'auto' | 'manual'

export interface ProductTourStep {
    id: string
    type: ProductTourStepType
    /** CSS selector for element steps, empty/undefined for modal/survey steps */
    selector?: string
    /** Rich text content in tiptap JSONContent format */
    content: Record<string, any> | null
    /** Pre-rendered HTML content for SDK consumption. Built from `content` on tour save. */
    contentHtml?: string
    /** Tooltip position relative to element - for element steps */
    position?: 'top' | 'bottom' | 'left' | 'right'
    /** Modal position on screen - for modal/survey steps */
    modalPosition?: ScreenPosition
    /** Inline survey question config - only for survey steps */
    survey?: ProductTourSurveyQuestion
    /** ID of the auto-created survey for this step (set by backend) */
    linkedSurveyId?: string
    /** how this step progresses, e.g. next button or click trigger */
    progressionTrigger?: ProductTourProgressionTriggerType
    /** Custom width for the tooltip - can be a preset name or pixel value */
    maxWidth?: ProductTourStepWidth | number
    /** Screenshot media ID from uploaded_media - for element steps */
    screenshotMediaId?: string
    /** enhanced element data for more reliable lookup at runtime */
    inferenceData?: InferredSelector
    /** SDK-only: derived from elementTargeting on save. Do not read directly in editor code. */
    useManualSelector?: boolean
    /** Editor-only: explicit targeting mode. Derived from legacy fields on load via normalizeStep(). */
    elementTargeting?: ProductTourStepTargeting
    /** Button configuration for tour steps (modals / announcements) */
    buttons?: ProductTourStepButtons
    /** Banner configuration (only for banner steps) */
    bannerConfig?: ProductTourBannerConfig
    /** translation data for this tour step, keyed on BCP 47 language code. */
    translations?: Record<string, ProductTourStepTranslation>
}

/** all translatable content for a given tour step */
export interface ProductTourStepTranslation {
    content?: ProductTourStep['content']
    contentHtml?: ProductTourStep['contentHtml']
    buttons?: {
        primary?: Pick<ProductTourStepButton, 'text'>
        secondary?: Pick<ProductTourStepButton, 'text'>
    }
    survey?: Pick<
        ProductTourSurveyQuestion,
        'questionText' | 'lowerBoundLabel' | 'upperBoundLabel' | 'submitButtonText' | 'backButtonText'
    >
}

/** Tracks a snapshot of steps at a point in time for funnel analysis */
export interface StepOrderVersion {
    id: string
    /** Full snapshot of steps as they existed when this version was created */
    steps: ProductTourStep[]
    /** When this version became active */
    created_at: string
}

export type EffectiveProductTourType = 'tour' | 'announcement' | 'banner'

export interface ProductTourWaitPeriod {
    days: number
    types: EffectiveProductTourType[]
}

export interface ProductTourDisplayConditions {
    url?: string
    urlMatchType?: SurveyMatchType
    selector?: string
    autoShowDelaySeconds?: number
    actions?: {
        values: {
            id: number
            name: string
        }[]
    } | null
    events?: {
        values: SurveyEventsWithProperties[]
    } | null
    cancelEvents?: {
        values: SurveyEventsWithProperties[]
    } | null
    linkedFlagVariant?: string
    seenTourWaitPeriod?: ProductTourWaitPeriod
    deviceTypes?: string[]
}

export interface ProductTourAppearance {
    backgroundColor?: string
    textColor?: string
    buttonColor?: string
    borderRadius?: number
    buttonBorderRadius?: number
    borderColor?: string
    fontFamily?: string
    boxShadow?: string
    showOverlay?: boolean
    whiteLabel?: boolean
    /** defaults to true, auto-set to false for announcements/banners */
    dismissOnClickOutside?: boolean
    zIndex?: number
}

export type ProductTourType = 'tour' | 'announcement'

export type ProductTourDisplayFrequency = 'show_once' | 'until_interacted' | 'always'

export interface ProductTourGeneratedStepContent {
    step_id: string
    title: string
    description: string
}

export interface ProductTourAIGenerationResponse {
    steps: ProductTourGeneratedStepContent[]
}

export interface ProductTourContent {
    type?: ProductTourType
    steps: ProductTourStep[]
    appearance?: ProductTourAppearance
    conditions?: ProductTourDisplayConditions
    /** History of step order changes for funnel analysis */
    step_order_history?: StepOrderVersion[]
    displayFrequency?: ProductTourDisplayFrequency
    /**
     * list of supported languages (BCP 47 syntax).
     *
     * only used for the builder UX.
     * sdk reads ProductTourStep.translations[langCode]
     * */
    languages?: string[]
}

export type ProductTourDraftContent = Partial<
    Pick<ProductTour, 'name' | 'description' | 'content' | 'auto_launch' | 'targeting_flag_filters' | 'linked_flag_id'>
>

export interface ProductTour {
    id: string
    name: string
    description: string
    internal_targeting_flag: FeatureFlagBasicType | null
    targeting_flag_filters: FeatureFlagFilters | null
    linked_flag: FeatureFlagBasicType | null
    linked_flag_id: number | null
    content: ProductTourContent
    auto_launch: boolean
    start_date: string | null
    end_date: string | null
    created_at: string
    created_by: UserBasicType | null
    updated_at: string
    archived: boolean
    draft_content: ProductTourDraftContent | null
    has_draft: boolean
}

export interface Survey extends WithAccessControl {
    /** UUID */
    id: string
    name: string
    type: SurveyType
    description: string
    schedule?: SurveySchedule | null
    linked_flag_id: number | null
    linked_flag: FeatureFlagBasicType | null
    targeting_flag: FeatureFlagBasicType | null
    targeting_flag_filters?: FeatureFlagFilters
    linked_insight_id?: number | null
    conditions: SurveyDisplayConditions | null
    appearance: SurveyAppearance | null
    questions: (BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion)[]
    created_at: string
    created_by: UserBasicType | null
    start_date: string | null
    end_date: string | null
    archived: boolean
    remove_targeting_flag?: boolean
    responses_limit: number | null
    iteration_count?: number | null
    iteration_frequency_days?: number | null
    iteration_start_dates?: string[]
    current_iteration?: number | null
    current_iteration_start_date?: string
    response_sampling_start_date?: string | null
    response_sampling_interval_type?: string | null
    response_sampling_interval?: number | null
    response_sampling_limit?: number | null
    response_sampling_daily_limits?: string[] | null
    enable_partial_responses?: boolean | null
    enable_iframe_embedding?: boolean | null
    _create_in_folder?: string | null
    headline_summary?: string | null
    headline_response_count?: number | null
    form_content?: Record<string, unknown> | null
    base_language?: string | null
    translations?: Record<
        string,
        {
            name?: string
            thankYouMessageHeader?: string
            thankYouMessageDescription?: string
            thankYouMessageCloseButtonText?: string
            introScreenHeader?: string
            introScreenDescription?: string
            introScreenButtonText?: string
            submitButtonText?: string
            backButtonText?: string
        }
    > | null
}

export enum SurveyMatchType {
    Exact = PropertyOperator.Exact,
    IsNot = PropertyOperator.IsNot,
    Contains = PropertyOperator.IContains,
    NotIContains = PropertyOperator.NotIContains,
    Regex = PropertyOperator.Regex,
    NotRegex = PropertyOperator.NotRegex,
}

export enum SurveyType {
    Popover = 'popover',
    Widget = 'widget', // feedback button survey
    FullScreen = 'full_screen',
    API = 'api',
    ExternalSurvey = 'external_survey',
}

export enum SurveyPosition {
    TopLeft = 'top_left',
    TopCenter = 'top_center',
    TopRight = 'top_right',
    MiddleLeft = 'middle_left',
    MiddleCenter = 'middle_center',
    MiddleRight = 'middle_right',
    Left = 'left',
    Center = 'center',
    Right = 'right',
    NextToTrigger = 'next_to_trigger',
}

export type ScreenPosition = Exclude<SurveyPosition, SurveyPosition.NextToTrigger>

export enum SurveyTabPosition {
    Top = 'top',
    Left = 'left',
    Right = 'right',
    Bottom = 'bottom',
}

export enum SurveyWidgetType {
    Button = 'button',
    Tab = 'tab',
    Selector = 'selector',
}

export type SurveyQuestionDescriptionContentType = 'html' | 'text'

export interface SurveyAppearance {
    backgroundColor?: string
    // Optional override for main survey text color. If not set, auto-calculated from backgroundColor.
    textColor?: string
    submitButtonColor?: string
    // TODO: remove submitButtonText in favor of buttonText once it's more deprecated
    submitButtonText?: string
    submitButtonTextColor?: string
    ratingButtonColor?: string
    ratingButtonActiveColor?: string
    borderColor?: string
    placeholder?: string
    whiteLabel?: boolean
    // Not a question: dismissing the intro records no response and never counts toward completion metrics.
    displayIntroScreen?: boolean
    introScreenHeader?: string
    introScreenDescription?: string
    introScreenDescriptionContentType?: SurveyQuestionDescriptionContentType
    introScreenButtonText?: string
    displayThankYouMessage?: boolean
    thankYouMessageHeader?: string
    thankYouMessageDescription?: string
    thankYouMessageDescriptionContentType?: SurveyQuestionDescriptionContentType
    thankYouMessageCloseButtonText?: string
    autoDisappear?: boolean
    position?: SurveyPosition
    tabPosition?: SurveyTabPosition
    zIndex?: string
    shuffleQuestions?: boolean
    surveyPopupDelaySeconds?: number
    allowGoBack?: boolean
    backButtonText?: string
    // widget only
    widgetType?: SurveyWidgetType
    widgetSelector?: string
    widgetLabel?: string
    widgetColor?: string
    fontFamily?: (typeof WEB_SAFE_FONTS)[number]['value']
    disabledButtonOpacity?: string
    maxWidth?: string
    textSubtleColor?: string
    inputBackground?: string
    // Optional override for input and rating button text color. If not set, auto-calculated from inputBackground.
    inputTextColor?: string
    boxPadding?: string
    boxShadow?: string
    borderRadius?: string
    // supported in the js sdk, NOT user-configurable.
    // only used for survey branching display.
    hideCancelButton?: boolean
}

export interface SurveyQuestionBase {
    question: string
    id?: string
    description?: string | null
    descriptionContentType?: SurveyQuestionDescriptionContentType
    optional?: boolean
    buttonText?: string
    branching?:
        | NextQuestionBranching
        | ConfirmationMessageBranching
        | ResponseBasedBranching
        | SpecificQuestionBranching
    translations?: Record<
        string,
        {
            question?: string
            description?: string
            buttonText?: string
            lowerBoundLabel?: string
            upperBoundLabel?: string
            choices?: string[]
            link?: string
        }
    > | null
}

export interface BasicSurveyQuestion extends SurveyQuestionBase {
    type: SurveyQuestionType.Open
    validation?: SurveyValidationRule[]
}

export interface LinkSurveyQuestion extends SurveyQuestionBase {
    type: SurveyQuestionType.Link
    link: string | null
}

export interface RatingSurveyQuestion extends SurveyQuestionBase {
    type: SurveyQuestionType.Rating
    display: 'number' | 'emoji'
    scale: SurveyRatingScaleValue
    lowerBoundLabel: string
    upperBoundLabel: string
    isNpsQuestion?: boolean
    skipSubmitButton?: boolean
    branching?:
        | NextQuestionBranching
        | ConfirmationMessageBranching
        | ResponseBasedBranching
        | SpecificQuestionBranching
}

export interface MultipleSurveyQuestion extends SurveyQuestionBase {
    type: SurveyQuestionType.SingleChoice | SurveyQuestionType.MultipleChoice
    choices: string[]
    shuffleOptions?: boolean
    hasOpenChoice?: boolean
    skipSubmitButton?: boolean
    branching?:
        | NextQuestionBranching
        | ConfirmationMessageBranching
        | ResponseBasedBranching
        | SpecificQuestionBranching
}

export type SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion

export enum SurveyQuestionType {
    Open = 'open',
    MultipleChoice = 'multiple_choice',
    SingleChoice = 'single_choice',
    Rating = 'rating',
    Link = 'link',
}

export enum SurveyValidationType {
    MinLength = 'min_length',
    MaxLength = 'max_length',
}

export interface SurveyValidationRule {
    type: SurveyValidationType
    value?: number
    errorMessage?: string
}

export enum SurveyQuestionBranchingType {
    NextQuestion = 'next_question',
    End = 'end',
    ResponseBased = 'response_based',
    SpecificQuestion = 'specific_question',
}

interface NextQuestionBranching {
    type: SurveyQuestionBranchingType.NextQuestion
}

interface ConfirmationMessageBranching {
    type: SurveyQuestionBranchingType.End
}

interface ResponseBasedBranching {
    type: SurveyQuestionBranchingType.ResponseBased
    responseValues: Record<string, any>
}

interface SpecificQuestionBranching {
    type: SurveyQuestionBranchingType.SpecificQuestion
    index: number
}

export interface FeatureFlagGroupType {
    properties?: AnyPropertyFilter[]
    rollout_percentage?: number | null
    variant?: string | null
    users_affected?: number
    sort_key?: string | null // Client-side only stable id for sorting.
    description?: string | null
    aggregation_group_type_index?: integer | null
    /** Stamped by the experiment exposure freeze: the group carries a machine-added snapshot-cohort condition. */
    exposure_frozen?: boolean
    /** Snapshot cohort the exposure freeze AND'd into this group's properties. */
    exposure_frozen_cohort?: number
}

export interface MultivariateFlagVariant {
    key: string
    name?: string | null
    rollout_percentage: number
}

export interface MultivariateFlagOptions {
    variants: MultivariateFlagVariant[]
}

export enum FeatureFlagEvaluationRuntime {
    SERVER = 'server',
    CLIENT = 'client',
    ALL = 'all',
}

export enum FeatureFlagBucketingIdentifier {
    DISTINCT_ID = 'distinct_id',
    DEVICE_ID = 'device_id',
}

/** Config version 1: release conditions, variants and payloads. Stored without a `version` key. */
export interface FeatureFlagFilters {
    version?: 1
    groups: FeatureFlagGroupType[]
    multivariate?: MultivariateFlagOptions | null
    aggregation_group_type_index?: integer | null
    payloads?: Record<string, JsonType>
    early_exit?: boolean
    feature_enrollment?: boolean
    /** Experiment holdout exclusion, evaluated by the flag matcher before release conditions. */
    holdout?: { id: number; exclusion_percentage: number } | null
    /** Legacy holdout representation, also evaluated before release conditions. */
    holdout_groups?: FeatureFlagGroupType[] | null
    /** Early access enrollment conditions, evaluated before release conditions. */
    super_groups?: FeatureFlagGroupType[] | null
}

/**
 * Declares the v1 keys absent on other versions, so optional reads compile on the union and return undefined for them.
 * Narrow with `isV1FeatureFlagConfig` to use the v1 shape.
 */
interface WithoutFeatureFlagFiltersKeys {
    groups?: never
    multivariate?: never
    payloads?: never
    early_exit?: never
    feature_enrollment?: never
    holdout?: never
    holdout_groups?: never
    super_groups?: never
}

export type FeatureFlagRulesV2ReturnType = 'boolean' | 'string' | 'number' | 'object'

interface FeatureFlagRulesV2RuleBase {
    id: string
    targeting: { properties: AnyPropertyFilter[] }
    description?: string
    metadata?: Record<string, unknown>
}

interface FeatureFlagRulesV2RolloutFields {
    rollout_percentage: number
    on_rollout_miss: 'continue' | 'return_default'
    assignment_algorithm: string
    seed: string
    assign_by?: 'person'
}

export interface FeatureFlagRulesV2TargetedReleaseRule extends FeatureFlagRulesV2RuleBase {
    rule_type: 'targeted_release'
    value: JsonType
}

export interface FeatureFlagRulesV2PercentageRolloutRule
    extends FeatureFlagRulesV2RuleBase, FeatureFlagRulesV2RolloutFields {
    rule_type: 'percentage_rollout'
    value: JsonType
}

export interface FeatureFlagRulesV2Variant {
    key: string
    /** Percentage of the subjects the rule enrolls; the weights of a rule total 100. */
    weight: number
    value: JsonType
}

/** Belongs to its rule. The seed is server-owned. */
export interface FeatureFlagRulesV2Holdout {
    seed: string
    exclusion_percentage: number
}

/** Serves the values of its variants. An experiment links to its rule, so the rule never names an experiment. */
export interface FeatureFlagRulesV2ExperimentRule extends FeatureFlagRulesV2RuleBase, FeatureFlagRulesV2RolloutFields {
    rule_type: 'experiment'
    paused: boolean
    variants: FeatureFlagRulesV2Variant[]
    holdout?: FeatureFlagRulesV2Holdout
}

export type FeatureFlagRulesV2Rule =
    | FeatureFlagRulesV2TargetedReleaseRule
    | FeatureFlagRulesV2PercentageRolloutRule
    | FeatureFlagRulesV2ExperimentRule

/** Config version 2: an ordered rule list. Read-only in this frontend; the API returns it under `filters` unchanged. */
export interface FeatureFlagRulesV2Config extends WithoutFeatureFlagFiltersKeys {
    version: 2
    return_type: FeatureFlagRulesV2ReturnType
    default_value: JsonType | null
    rules: FeatureFlagRulesV2Rule[]
    aggregation_group_type_index?: integer | null
}

export interface FeatureFlagUnsupportedConfig extends WithoutFeatureFlagFiltersKeys {
    version: number
    aggregation_group_type_index?: never
}

/**
 * A rule while the editor drafts it. A new rule has no `id`, and a new rollout or holdout no `seed`, until the server
 * assigns them. A stored rule keeps both, and every field the editor does not render, as it was loaded.
 */
export type FeatureFlagRulesV2DraftRule =
    | (Omit<FeatureFlagRulesV2TargetedReleaseRule, 'id'> & { id?: string })
    | (Omit<FeatureFlagRulesV2PercentageRolloutRule, 'id' | 'seed'> & { id?: string; seed?: string })
    | (Omit<FeatureFlagRulesV2ExperimentRule, 'id' | 'seed' | 'holdout'> & {
          id?: string
          seed?: string
          holdout?: FeatureFlagRulesV2DraftHoldout
      })

export type FeatureFlagRulesV2DraftExperimentRule = Extract<FeatureFlagRulesV2DraftRule, { rule_type: 'experiment' }>

export type FeatureFlagRulesV2DraftHoldout = Omit<FeatureFlagRulesV2Holdout, 'seed'> & { seed?: string }

export interface FeatureFlagRulesV2DraftConfig extends Omit<FeatureFlagRulesV2Config, 'rules'> {
    rules: FeatureFlagRulesV2DraftRule[]
}

/** What the API stores under a flag's `filters`, discriminated by `version` (absent means 1). */
export type FeatureFlagConfig = FeatureFlagFilters | FeatureFlagRulesV2Config | FeatureFlagUnsupportedConfig

export interface FeatureFlagBasicType {
    id: number
    team_id: TeamType['id']
    key: string
    /* The description field (the name is a misnomer because of its legacy). */
    name: string
    filters: FeatureFlagConfig
    deleted: boolean
    active: boolean
    ensure_experience_continuity: boolean | null
}

export interface FeatureFlagType extends Omit<FeatureFlagBasicType, 'id' | 'team_id'>, WithAccessControl {
    /** Null means that the flag has never been saved yet (it's new). */
    id: number | null
    created_by: UserBasicType | null
    created_at: string | null
    updated_at: string | null
    version: number | null
    last_modified_by: UserBasicType | null
    experiment_set: number[] | null
    experiment_set_metadata: { id: number; name: string; is_running: boolean }[] | null
    features: MinimalEarlyAccessFeatureType[] | null
    surveys: Survey[] | null
    /** Archived flags are hidden from the flag list by default and must be disabled. */
    archived: boolean
    can_edit: boolean
    tags: string[]
    evaluation_contexts: string[]
    usage_dashboard?: number | null
    has_enriched_analytics?: boolean
    is_remote_configuration: boolean
    has_encrypted_payloads: boolean
    status: 'ACTIVE' | 'STALE' | 'ARCHIVED' | 'DELETED' | 'UNKNOWN'
    _create_in_folder?: string | null
    evaluation_runtime: FeatureFlagEvaluationRuntime
    bucketing_identifier?: FeatureFlagBucketingIdentifier | null
    last_called_at?: string | null
    is_used_in_replay_settings?: boolean
}

export type FeatureFlagWithV1Config = FeatureFlagType & { filters: FeatureFlagFilters }

export interface OrganizationFeatureFlag {
    flag_id: number | null
    team_id: number | null
    created_by: UserBasicType | null
    created_at: string | null
    filters: FeatureFlagConfig
    active: boolean
    evaluations_7d?: number | null
}

export interface OrganizationFeatureFlagRow {
    id: number
    team_id: number
    key: string
    name: string
    // active + filters power the instant first paint of the current team's cell and are free
    // (already on the row). created_by/created_at are omitted: the grid never renders them, and
    // serializing created_by would force a per-row join.
    active: boolean
    filters: FeatureFlagConfig
}

export interface OrganizationFeatureFlagKeysResponse {
    count: number
    next: string | null
    previous: string | null
    results: OrganizationFeatureFlagRow[]
}

export interface OrganizationFeatureFlagsCopyBody {
    feature_flag_key: FeatureFlagType['key']
    from_project: TeamType['id']
    target_project_ids: TeamType['id'][]
    copy_schedule?: boolean
    disable_copied_flag?: boolean
}

export enum FeatureFlagStatus {
    ACTIVE = 'active',
    STALE = 'stale',
    ARCHIVED = 'archived',
    DELETED = 'deleted',
    UNKNOWN = 'unknown',
}

export interface CombinedFeatureFlagAndValueType {
    feature_flag: FeatureFlagType
    value: boolean | string
}

export interface Feature {
    id: number | null
    name: string
}

export enum EarlyAccessFeatureStage {
    Draft = 'draft',
    Concept = 'concept',
    Alpha = 'alpha',
    Beta = 'beta',
    GeneralAvailability = 'general-availability',
    Archived = 'archived',
}

export enum EarlyAccessFeatureTabs {
    OptedIn = 'opted-in',
    OptedOut = 'opted-out',
}

export type EarlyAccessFeatureAssigneeType = 'user' | 'role'

/** Person or role an early access feature is assigned to. Defaults to the creator. */
export interface EarlyAccessFeatureAssignee {
    type: EarlyAccessFeatureAssigneeType
    id: number | string
}

export interface EarlyAccessFeatureType {
    /** UUID */
    id: string
    feature_flag: FeatureFlagBasicType
    name: string
    description: string
    stage: EarlyAccessFeatureStage
    /** Documentation URL. Can be empty. */
    documentation_url: string
    /** Custom JSON payload for the early access feature */
    payload?: Record<string, any>
    created_at: string
    /** The user who created this feature. Null for features created before creator tracking was added. */
    created_by?: UserBasicType | null
    assignee?: EarlyAccessFeatureAssignee | null
    _create_in_folder?: string | null
    /** The effective access level the user has for this early access feature. */
    user_access_level?: AccessControlLevel
}

export interface NewEarlyAccessFeatureType extends Omit<EarlyAccessFeatureType, 'id' | 'created_at' | 'feature_flag'> {
    feature_flag_id: number | undefined
}

/** Shape served by MinimalEarlyAccessFeatureSerializer (camelCase keys), e.g. as `FeatureFlagType.features`. */
export interface MinimalEarlyAccessFeatureType {
    id: string
    name: string
    description: string
    stage: EarlyAccessFeatureStage
    documentationUrl: string
    flagKey: string | null
    payload?: Record<string, any>
}

export interface UserBlastRadiusType {
    affected: number
    total: number
}

export enum ScheduledChangeModels {
    FeatureFlag = 'FeatureFlag',
}

export enum ScheduledChangeOperationType {
    UpdateStatus = 'update_status',
    AddReleaseCondition = 'add_release_condition',
    UpdateVariants = 'update_variants',
}

// Keep in sync with products/feature_flags/backend/models/scheduled_change.py RecurrenceInterval
export enum RecurrenceInterval {
    Daily = 'daily',
    Weekly = 'weekly',
    Monthly = 'monthly',
    Yearly = 'yearly',
}

export type ScheduledChangePayload =
    | { operation: ScheduledChangeOperationType.UpdateStatus; value: boolean }
    | {
          operation: ScheduledChangeOperationType.AddReleaseCondition
          value: FeatureFlagFilters
      }
    | {
          operation: ScheduledChangeOperationType.UpdateVariants
          value: {
              variants: MultivariateFlagVariant[]
              payloads?: Record<string, any>
          }
      }

// Keep in sync with products/approvals/backend/models.py ChangeRequestState
export enum ScheduledChangeRequestState {
    Pending = 'pending',
    Approved = 'approved',
    Applied = 'applied',
    Rejected = 'rejected',
    Expired = 'expired',
    Failed = 'failed',
}

/** Summary of the approval change request gating a scheduled change. */
export interface ScheduledChangeRequestSummary {
    id: string
    state: ScheduledChangeRequestState
}

export interface ScheduledChangeType {
    id: number
    team_id: number
    record_id: number | string
    model_name: ScheduledChangeModels
    payload: ScheduledChangePayload
    scheduled_at: string
    executed_at: string | null
    failure_reason: string | null
    created_at: string | null
    created_by: UserBasicType
    is_recurring: boolean
    recurrence_interval: RecurrenceInterval | null
    cron_expression: string | null
    last_executed_at: string | null
    end_date: string | null
    /** Null when the change is not gated on approval. */
    change_request: ScheduledChangeRequestSummary | null
}

export interface PrevalidatedInvite {
    id: string
    target_email: string
    first_name: string
    organization_name: string
}

interface InstancePreferencesInterface {
    /** Whether debug queries option should be shown on the command palette. */
    debug_queries: boolean
    /** Whether paid features showcasing / upsells are completely disabled throughout the app. */
    disable_paid_fs: boolean
    /** Whether Cloudflare proxy is enabled for managed reverse proxies. */
    cloudflare_proxy_enabled?: boolean
}

export interface PreflightStatus {
    // Attributes that accept undefined values (i.e. `?`) are not received when unauthenticated
    django: boolean
    plugins: boolean
    redis: boolean
    db: boolean
    clickhouse: boolean
    kafka: boolean
    /** An initiated instance is one that already has any organization(s). */
    initiated: boolean
    /** Org creation is allowed on Cloud OR initiated self-hosted organizations with a license and MULTI_ORG_ENABLED. */
    can_create_org: boolean
    /** Whether this is PostHog Cloud. */
    cloud: boolean
    /** Whether this is a managed demo environment. */
    demo: boolean
    celery: boolean
    realm: Realm
    region: Region | null
    available_social_auth_providers: AuthBackends
    available_timezones?: Record<string, number>
    opt_out_capture?: boolean
    email_service_available: boolean
    slack_service: {
        available: boolean
        client_id?: string
    }
    data_warehouse_integrations: {
        hubspot: {
            client_id?: string
        }
        salesforce: {
            client_id?: string
        }
    }
    /** Whether PostHog is running in settings.DEBUG or settings.E2E_TESTING. */
    is_debug?: boolean
    /** Whether one-click dev login is enabled (DEBUG and ALLOW_DEV_LOGIN). */
    allow_dev_login?: boolean
    /** Whether PostHog is running with settings.TEST. */
    is_test?: boolean
    licensed_users_available?: number | null
    openai_available?: boolean
    anthropic_available?: boolean
    site_url?: string
    instance_preferences?: InstancePreferencesInterface
    buffer_conversion_seconds?: number
    cohort_csv_upload_max_bytes?: number
    /** Whether the instance has an MCP server that the WebMCP proxy can reach. */
    webmcp_available?: boolean
    object_storage: boolean
    wizard_cloud_run_available: boolean
    public_egress_ip_addresses?: string[]
    dev_disable_navigation_hooks?: boolean
}

// TODO: Consolidate this and DashboardMode
export enum ItemMode {
    Edit = 'edit',
    View = 'view',
    Subscriptions = 'subscriptions',
    Sharing = 'sharing',
    Alerts = 'alerts',
}

export enum DashboardPlacement {
    Dashboard = 'dashboard', // When on the standard dashboard page
    CustomerAnalytics = 'customer-analytics', // When embedded on the customer analytics page
    ProjectHomepage = 'project-homepage', // When embedded on the project homepage
    FeatureFlag = 'feature-flag',
    Public = 'public', // When viewing the dashboard publicly
    Export = 'export', // When the dashboard is being exported (alike to being printed)
    Person = 'person', // When the dashboard is being viewed on a person page
    Group = 'group', // When the dashboard is being viewed on a group page
    Builtin = 'builtin', // Dashboard built into product UI with external controls provided by parent context
    DataOps = 'data-ops', // When embedded on the data ops scene dashboard tab
}

// Default mode is null
export enum DashboardMode {
    Fullscreen = 'fullscreen', // When the dashboard is on full screen (presentation) mode
    Sharing = 'sharing', // When the sharing configuration is opened
}

// Hotkeys for local (component) actions
export type HotKey =
    | 'a'
    | 'b'
    | 'c'
    | 'd'
    | 'e'
    | 'f'
    | 'g'
    | 'h'
    | 'i'
    | 'j'
    | 'k'
    | 'l'
    | 'm'
    | 'n'
    | 'o'
    | 'p'
    | 'q'
    | 'r'
    | 's'
    | 't'
    | 'u'
    | 'v'
    | 'w'
    | 'x'
    | 'y'
    | 'z'
    | '0'
    | '1'
    | '2'
    | '3'
    | '4'
    | '5'
    | '6'
    | '7'
    | '8'
    | '9'
    | 'escape'
    | 'enter'
    | 'space'
    | 'tab'
    | 'arrowleft'
    | 'arrowright'
    | 'arrowdown'
    | 'arrowup'
    | 'forwardslash'
    | 'minus'
    | 'delete'
    | 'atsign'
export type HotKeyOrModifier = HotKey | 'shift' | 'option' | 'command'

export enum SchemaEnforcementMode {
    Allow = 'allow',
    Reject = 'reject',
}

export interface EventDefinition {
    id: string
    name: string
    description?: string
    tags?: string[]
    owner?: UserBasicType | null
    created_at?: string
    last_seen_at?: string
    last_updated_at?: string // alias for last_seen_at to achieve event and action parity
    updated_at?: string
    updated_by?: UserBasicType | null
    verified?: boolean
    verified_at?: string
    verified_by?: string
    is_action?: boolean
    is_data_warehouse?: boolean
    hidden?: boolean
    default_columns?: string[]
    enforcement_mode?: SchemaEnforcementMode
    media_preview_urls?: string[]
    /** Name of a single property on this event to display alongside it in PostHog UI surfaces. */
    primary_property?: string | null
}

export interface EventDefinitionMetrics {
    query_usage_30_day: number
}

export interface ObjectMediaPreview {
    id: string
    created_at: string
    updated_at: string
    media_url: string
    media_type: 'uploaded' | 'exported'
    metadata?: Record<string, any>
}

export enum PropertyType {
    DateTime = 'DateTime',
    String = 'String',
    Numeric = 'Numeric',
    Boolean = 'Boolean',
    Duration = 'Duration',
    Selector = 'Selector',
    Cohort = 'Cohort',
    Assignee = 'Assignee',
    StringArray = 'StringArray',
    Flag = 'Flag',
    Semver = 'Semver',
}

export enum PropertyDefinitionType {
    Event = 'event',
    EventMetadata = 'event_metadata',
    RevenueAnalytics = 'revenue_analytics',
    Account = 'account',
    AccountRelationship = 'account_relationship',
    AccountCustomProperty = 'account_custom_property',
    Person = 'person',
    PersonMetadata = 'person_metadata',
    Group = 'group',
    Session = 'session',
    LogEntry = 'log_entry',
    Meta = 'meta',
    Resource = 'resource',
    Log = 'log',
    LogAttribute = 'log_attribute',
    LogResourceAttribute = 'log_resource_attribute',
    MetricAttribute = 'metric_attribute',
    Span = 'span',
    SpanAttribute = 'span_attribute',
    SpanResourceAttribute = 'span_resource_attribute',
    FlagValue = 'flag_value',
    WorkflowVariable = 'workflow_variable',
}

export interface PropertyDefinition {
    id: string
    name: string
    description?: string
    tags?: string[]
    updated_at?: string
    updated_by?: UserBasicType | null
    is_numerical?: boolean // Marked as optional to allow merge of EventDefinition & PropertyDefinition
    is_seen_on_filtered_events?: boolean // Indicates whether this property has been seen for a particular set of events (when `eventNames` query string is sent); calculated at query time, not stored in the db
    property_type?: PropertyType
    type?: PropertyDefinitionType
    created_at?: string // TODO: Implement
    last_seen_at?: string // TODO: Implement
    example?: string
    is_action?: boolean
    verified?: boolean
    verified_at?: string
    verified_by?: string
    hidden?: boolean
    virtual?: boolean
    // Provenance when a person property is populated from a data warehouse source. Read-only.
    warehouse_origin?: WarehousePropertyOrigin | null
}

export interface WarehousePropertyOrigin {
    source_id?: string
    schema_id?: string
    table_name?: string
    column?: string
    custom_property_source_id?: string
    last_synced_at?: string
}

export enum PropertyDefinitionState {
    Pending = 'pending',
    Loading = 'loading',
    Missing = 'missing',
    Error = 'error',
}

export type PropertyDefinitionVerificationStatus = 'verified' | 'hidden' | 'visible'
export type Definition = EventDefinition | PropertyDefinition

export interface PersonProperty {
    id: number
    name: string
    count: number
}

export type GroupTypeIndex = 0 | 1 | 2 | 3 | 4

export type LabelGroupType = GroupTypeIndex | 'people'

export interface GroupType {
    group_type: string
    group_type_index: GroupTypeIndex
    name_singular?: string | null
    name_plural?: string | null
    detail_dashboard?: number | null
    default_columns?: string[]
}

export type GroupTypeProperties = Record<number, Array<PersonProperty>>

export interface Group {
    created_at: string
    group_key: string
    group_type_index: GroupTypeIndex
    group_properties: Record<string, any>
    notebook: string | null
}

export enum ExperimentConclusion {
    Won = 'won',
    Lost = 'lost',
    Inconclusive = 'inconclusive',
    StoppedEarly = 'stopped_early',
    Invalid = 'invalid',
}

export interface ExperimentHoldoutType {
    /** @asType integer */
    id: number | null
    name: string
    description: string | null
    filters: FeatureFlagGroupType[]
    created_by: UserBasicType | null
    created_at: string | null
    updated_at: string | null
    /** Read-only, server-computed effective access level; absent on a not-yet-created holdout. */
    user_access_level?: AccessControlLevel
}

export enum ExperimentStatsMethod {
    Bayesian = 'bayesian',
    Frequentist = 'frequentist',
}

export interface ExperimentExposureEstimateConfig {
    conversionRateInputType: ConversionRateInputType
    manualMetricType?: 'funnel' | 'mean_count' | 'mean_sum_or_avg'
    manualBaselineValue?: number
    manualExposureRate?: number
}

export interface ExperimentRunningTimeCalculationConfig {
    minimum_detectable_effect?: number
    recommended_running_time?: number
    recommended_sample_size?: number
    exposure_estimate_config?: ExperimentExposureEstimateConfig | null
}

export interface Experiment {
    id: ExperimentIdType
    name: string
    type?: string
    description?: string
    feature_flag_key: string
    feature_flag?: FeatureFlagBasicType
    /**
     * Draft flag config for an unsaved experiment, in the flag's own input shape. Client-only:
     * `toExperimentWritePayload` extracts it into the `feature_flag` write field and strips it.
     * Saved experiments read flag config from `feature_flag` (the read projection) instead.
     */
    feature_flag_config?: ExperimentFeatureFlagInputApi
    exposure_cohort?: number
    exposure_criteria?: ExperimentExposureCriteria
    filters: TrendsFilterType | FunnelsFilterType
    metrics: (ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery)[]
    metrics_secondary: (ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery)[]
    primary_metrics_ordered_uuids: string[] | null
    secondary_metrics_ordered_uuids: string[] | null
    saved_metrics_ids: {
        id: number
        metadata: { type: 'primary' | 'secondary' }
    }[]
    saved_metrics: any[]
    parameters: {
        custom_exposure_filter?: FilterType
        variant_screenshot_media_ids?: Record<string, string[]>
        variant_notes?: Record<string, string>
        /** Present when the experiment was created from an LLM prompt via /create_from_prompt/. */
        prompt_metadata?: {
            name: string
            templates: string[]
            versions: number[]
        }
    }
    running_time_calculation?: ExperimentRunningTimeCalculationConfig
    /** Variant keys dropped from statistical analysis. Canonical home for what historically lived in `parameters.excluded_variants`. */
    excluded_variants?: string[] | null
    start_date?: string | null
    end_date?: string | null
    status?: ExperimentStatus | null
    /** Server-computed: whether the experiment uses any legacy-engine metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery). Present on every list and detail response; optional here because locally-constructed/new experiments don't set it (and are never legacy). */
    is_legacy?: boolean
    /** Server-computed: the event exposures are counted on when no custom exposure event is configured — `$feature_flag_called`, or `$experiment_exposure` once the team is in the rollout and the experiment started at or after the cutoff. Resolve display and filters through `experimentLogic`'s `resolvedExposureEvent` rather than reading this directly, so locally-constructed experiments still get a value. */
    resolved_exposure_event?: string
    archived?: boolean
    secondary_metrics: SecondaryExperimentMetric[]
    created_at: string | null
    created_by: UserBasicType | null
    updated_at: string | null
    holdout_id?: number | null
    holdout?: ExperimentHoldoutType
    stats_config?: {
        version?: number
        method?: ExperimentStatsMethod
        baseline_variant_key?: string
        bayesian?: {
            ci_level?: number
        }
        frequentist?: {
            alpha?: number
            sequential_testing_enabled?: boolean
            sequential_tuning_parameter?: number
        }
        cuped?: {
            enabled?: boolean
            lookback_days?: number
        }
    }
    only_count_matured_users?: boolean
    _create_in_folder?: string | null
    conclusion?: ExperimentConclusion | null
    conclusion_comment?: string | null
    /** Desktop task opened to remove the experiment's flag code, when requested on end/ship. */
    flag_cleanup_task_id?: string | null
    user_access_level: AccessControlLevel
    tags?: string[]
    /** Optimistic-concurrency token, bumped by the server on every update. Send the last-read
     * value with updates so concurrent edits are detected (409) or merged instead of clobbered. */
    version?: number | null
}

export interface ExperimentVelocityStats {
    launched_last_30d: number
    launched_previous_30d: number
    percent_change: number
    active_experiments: number
    completed_last_30d: number
}

export interface SecondaryExperimentMetric {
    name: string
    filters: Partial<FilterType>
}

export interface SelectOption {
    value: string
    label?: string
}

export enum FilterLogicalOperator {
    And = 'AND',
    Or = 'OR',
}

export interface PropertyGroupFilter {
    type: FilterLogicalOperator
    values: PropertyGroupFilterValue[]
}

export interface PropertyGroupFilterValue {
    type: FilterLogicalOperator
    values: (AnyPropertyFilter | PropertyGroupFilterValue)[]
}

/** One row of a filter editor. A group's values can nest, so a row is not always a leaf filter. */
export type PropertyFilterRow = AnyPropertyFilter | PropertyGroupFilterValue

export interface CohortCriteriaGroupFilter {
    id?: string
    type: FilterLogicalOperator
    values: AnyCohortCriteriaType[] | CohortCriteriaGroupFilter[]
    sort_key?: string // Client-side only stable id for sorting.
}

export interface SelectOptionWithChildren extends SelectOption {
    children: React.ReactChildren
    ['data-attr']: string
    key: string
}

export interface CoreFilterDefinition {
    label: string
    description?: string | ReactNode
    examples?: (string | number | boolean)[]
    /** System properties are hidden in properties table by default. */
    system?: boolean
    type?: PropertyType
    /** Virtual properties are not "sent as", because they are calculated from other properties or SQL expressions **/
    virtual?: boolean
    /** whether this is a property PostHog adds to aid with debugging */
    used_for_debug?: boolean
    /** Name of a single property on events of this name that UIs should display alongside the event. */
    primary_property?: string
    /** Keep this event out of pickers that build a query someone saves and runs later. Surfaces that read live event data still offer it. */
    hidden_in_query_builders?: boolean
}

export interface TileParams {
    title: string
    targetPath: string
    openInNewTab?: boolean
    hoverText?: string
    icon: JSX.Element
    class?: string
}

export interface TiledIconModuleProps {
    tiles: TileParams[]
    header?: string
    subHeader?: string
    analyticsModuleKey?: string
}

export type EventOrPropType = EventDefinition & PropertyDefinition

export interface AppContext {
    /** The page left out the user's data, and the app fetches it at boot. See lib/utils/deferredAppContext. */
    deferred?: boolean
    /** The user's variant in the deferred app context experiment. Absent outside the experiment. */
    deferred_app_context_variant?: string
    run_mode?: 'US' | 'EU' | 'DEV' | 'E2E' | 'LOCAL' | 'HOBBY'
    current_user: UserType | null
    current_project: ProjectType | null
    current_team: TeamType | TeamPublicType | null
    preflight: PreflightStatus
    default_event_name: string | null
    has_pageview: boolean
    has_screen: boolean
    /** Absent until the app context's full stage arrives. */
    has_person_email?: boolean
    /**
     * Flags the server bootstraps as enabled (a list of keys). Storybook may instead pass a
     * record to pin specific multivariate variants (e.g. an experiment arm) for a story.
     */
    persisted_feature_flags?: string[] | Record<string, string | boolean>
    /** Whether the server's access gate gives this user PostHog AI 2.0. Absent when no user is signed in. */
    posthog_ai_access?: boolean
    anonymous: boolean
    effective_resource_access_control: Record<AccessControlResourceType, AccessControlLevel>
    resource_access_control: Record<AccessControlResourceType, AccessControlLevel>
    commit_sha?: string
    /** Whether the user was autoswitched to the current item's team. */
    switched_team: TeamType['id'] | null
    /** Support flow aid: a staff-only list of users who may be impersonated to access this resource. */
    suggested_users_with_access?: UserBasicType[]
    /** The project the URL asked for, as an id or a token, when the server refused to switch to it. */
    project_access_denied?: string | null
    livestream_host?: string
    oauth_application?: OAuthApplicationPublicMetadata
    /** Server-resolved MCP scopes for OAuth consent when the client omits `scope`. */
    oauth_mcp_consent?: OAuthMcpConsentContext
    /** One of the user's organizations has the access-control feature and at least one rule, so a granted scope can reach less. */
    oauth_consent_access_controls_apply?: boolean
    /** The scope set `/authorize` resolved for this request; the consent screen must render this, not the URL's `scope`. */
    oauth_scope_resolution?: OAuthScopeResolution
    /** The user's configured homepage for the current team, bootstrapped so navigation can honor it on first paint. */
    homepage?: SceneTab | null
}

export type StoredMetricMathOperations = 'max' | 'min' | 'sum'

export interface PathEdgeParameters {
    edgeLimit?: number | undefined
    minEdgeWeight?: number | undefined
    maxEdgeWeight?: number | undefined
}

export enum HelpType {
    Slack = 'slack',
    GitHub = 'github',
    Email = 'email',
    Docs = 'docs',
    Updates = 'updates',
    SupportForm = 'support_form',
}

export interface DateMappingOption {
    key: string
    inactive?: boolean // Options removed due to low usage (see relevant PR); will not show up for new insights but will be kept for existing
    values: string[]
    getFormattedDate?: (date: dayjs.Dayjs, format?: string, weekStartDay?: number) => string
    defaultInterval?: IntervalType
}

interface BreadcrumbBase {
    /** E.g. scene, tab, or scene with item ID. Particularly important for `onRename`. */
    key: string | number | [scene: Scene | string, key: string | number]
    /** Whether to show a custom popover */
    popover?: Pick<PopoverProps, 'overlay' | 'matchWidth'>
    /** Whether to show a custom popover for the project */
    isPopoverProject?: boolean
    iconType?: FileSystemIconType | 'blank' | 'loading'
}
export interface LinkBreadcrumb extends BreadcrumbBase {
    /** Name to display. */
    name: string | JSX.Element | null | undefined
    symbol?: never
    /** Path to link to. */
    path?: string
    /** Extra tag shown next to name. */
    tag?: string | null
    onRename?: never
}
export interface RenamableBreadcrumb extends BreadcrumbBase {
    /** Name to display. */
    name: string | JSX.Element | null | undefined
    symbol?: never
    path?: never
    /** When this is set, an "Edit" button shows up next to the title */
    onRename?: (newName: string) => Promise<void>
    /** When this is true, the name is always in edit mode, and `onRename` runs on every input change. */
    forceEditMode?: boolean
}
export interface SymbolBreadcrumb extends BreadcrumbBase {
    name?: never
    /** Symbol, e.g. a lettermark or a profile picture. */
    symbol: React.ReactElement
    path?: never
}

export interface FileSystemDeletionSummary {
    type: string
    ref: string | null
    mode: 'soft' | 'hard'
    undo: string
    path: string
    can_undo: boolean
}

export interface FileSystemDeleteResponse {
    deleted: FileSystemDeletionSummary[]
}
export interface ProjectTreeBreadcrumb extends BreadcrumbBase {
    /** Last part of path */
    name: string
    /** Rest of the path. */
    path?: string
    type: string
    ref?: string
    symbol?: never
    onRename?: never
}
export type Breadcrumb = LinkBreadcrumb | RenamableBreadcrumb | SymbolBreadcrumb | ProjectTreeBreadcrumb

export type GraphDataset = Partial<
    Pick<
        TrendResult,
        | 'count'
        | 'label'
        | 'days'
        | 'labels'
        | 'data'
        | 'compare'
        | 'compare_label'
        | 'status'
        | 'order'
        | 'breakdown_value'
        | 'persons_urls'
        | 'persons'
    >
> & {
    /** Used in filtering out visibility of datasets. Set internally by chart.js */
    id: number
    /** Toggled on to draw incompleteness lines in LineGraph.tsx */
    dotted?: boolean
    /** Array of breakdown values used only in ActionsHorizontalBar/ActionsPie.tsx data */
    breakdownValues?: (string | number | string[] | undefined)[]
    /** Array of breakdown labels used only in ActionsHorizontalBar/ActionsPie.tsx data */
    breakdownLabels?: (string | number | undefined)[]
    /** Array of compare labels used only in ActionsHorizontalBar/ActionsPie.tsx data */
    compareLabels?: (CompareLabelType | undefined | null)[]
    /** Array of persons used only in (ActionsHorizontalBar|ActionsPie).tsx */
    personsValues?: (Person | undefined | null)[]
    index?: number
    /** Value (count) for specific data point; only valid in the context of an xy intercept */
    pointValue?: number
    /** Value (count) for specific data point; only valid in the context of an xy intercept */
    personUrl?: string
    yAxisID?: string
}

export enum CompareLabelType {
    Current = 'current',
    Previous = 'previous',
}

export interface InstanceSetting {
    key: string
    value: boolean | string | number | number[] | null
    value_type: 'bool' | 'str' | 'int' | 'list[int]'
    description?: string
    editable: boolean
    is_secret: boolean
}

export enum FunnelMathType {
    AnyMatch = 'total',
    FirstTimeForUser = 'first_time_for_user',
    FirstTimeForUserWithFilters = 'first_time_for_user_with_filters',
}

export enum BaseMathType {
    TotalCount = 'total',
    UniqueUsers = 'dau',
    WeeklyActiveUsers = 'weekly_active',
    MonthlyActiveUsers = 'monthly_active',
    UniqueSessions = 'unique_session',
    FirstTimeForUser = 'first_time_for_user',
    FirstMatchingEventForUser = 'first_matching_event_for_user',
}

export enum CalendarHeatmapMathType {
    TotalCount = 'total',
    UniqueUsers = 'dau',
}

export enum PropertyMathType {
    Average = 'avg',
    Sum = 'sum',
    Minimum = 'min',
    Maximum = 'max',
    Median = 'median',
    P75 = 'p75',
    P90 = 'p90',
    P95 = 'p95',
    P99 = 'p99',
}

export enum CountPerActorMathType {
    Average = 'avg_count_per_actor',
    Minimum = 'min_count_per_actor',
    Maximum = 'max_count_per_actor',
    Median = 'median_count_per_actor',
    P75 = 'p75_count_per_actor',
    P90 = 'p90_count_per_actor',
    P95 = 'p95_count_per_actor',
    P99 = 'p99_count_per_actor',
}

export enum HogQLMathType {
    HogQL = 'hogql',
}
export enum GroupMathType {
    UniqueGroup = 'unique_group',
    FirstTimeForGroup = 'first_time_for_group',
    FirstMatchingEventForGroup = 'first_matching_event_for_group',
}

export enum ExperimentMetricMathType {
    TotalCount = 'total',
    Sum = 'sum',
    UniqueSessions = 'unique_session',
    Min = 'min',
    Max = 'max',
    Avg = 'avg',
    UniqueUsers = 'dau',
    UniqueGroup = 'unique_group',
    HogQL = 'hogql',
}

export enum ExperimentMetricGoal {
    Increase = 'increase',
    Decrease = 'decrease',
}

export enum ActorGroupType {
    Person = 'person',
    GroupPrefix = 'group',
}

export enum BehavioralEventType {
    PerformEvent = 'performed_event',
    PerformMultipleEvents = 'performed_event_multiple',
    PerformSequenceEvents = 'performed_event_sequence',
    NotPerformedEvent = 'not_performed_event',
    NotPerformSequenceEvents = 'not_performed_event_sequence',
    HaveProperty = 'have_property',
    NotHaveProperty = 'not_have_property',
}

export enum BehavioralCohortType {
    InCohort = 'in_cohort',
    NotInCohort = 'not_in_cohort',
}

export enum BehavioralLifecycleType {
    PerformEventFirstTime = 'performed_event_first_time',
    PerformEventRegularly = 'performed_event_regularly',
    StopPerformEvent = 'stopped_performing_event',
    StartPerformEventAgain = 'restarted_performing_event',
}

export enum TimeUnitType {
    Day = 'day',
    Week = 'week',
    Month = 'month',
    Year = 'year',
}

export enum DateOperatorType {
    BeforeTheLast = 'before_the_last',
    Between = 'between',
    NotBetween = 'not_between',
    OnTheDate = 'on_the_date',
    NotOnTheDate = 'not_on_the_date',
    Since = 'since',
    Before = 'before',
    IsSet = 'is_set',
    IsNotSet = 'is_not_set',
}

export enum SingleFieldDateType {
    IsDateExact = 'is_date_exact',
    IsDateBefore = 'is_date_before',
    IsDateAfter = 'is_date_after',
}

export enum ValueOptionType {
    MostRecent = 'most_recent',
    Previous = 'previous',
    OnDate = 'on_date',
}

export type WeekdayType = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday'

export type SubscriptionResourceType = 'insight' | 'dashboard' | 'ai_prompt'
// Value map for the above — kept a distinct name from the type so kea-typegen still imports
// the type correctly (a const+type sharing a name drops it from generated `import type` lines).
export const SubscriptionResourceTypes = {
    Insight: 'insight',
    Dashboard: 'dashboard',
    AiPrompt: 'ai_prompt',
} as const satisfies Record<string, SubscriptionResourceType>

// TODO: migrate to SubscriptionApi from @posthog/products-subscriptions/frontend/generated/api.schemas.
// This hand-written interface predates the generated type and now requires
// dual-maintenance for every backend field change.
export interface SubscriptionType {
    id: number
    resource_type: SubscriptionResourceType
    insight?: number
    dashboard?: number
    insight_short_id?: string | null
    resource_name?: string | null
    dashboard_export_insights?: number[]
    integration_id?: number | null
    prompt?: string | null
    ai_prompt_config?: AIPromptConfigApi | null
    delivery_config?: DeliveryConfigApi
    target_type: string
    target_value: string
    frequency: 'daily' | 'weekly' | 'monthly' | 'yearly'
    interval: number
    byweekday: WeekdayType[] | null
    bysetpos: number | null
    start_date: string
    until_date?: string
    title: string
    summary: string
    next_delivery_date: string | null
    created_by?: UserBasicType | null
    created_at: string
    deleted?: boolean
    enabled?: boolean
    summary_enabled?: boolean
    summary_prompt_guide?: string
    /** Write-only. When false, creating the subscription skips the immediate confirmation send (the schedule is unaffected). */
    send_test_now?: boolean
}

export type SmallTimeUnit = 'hours' | 'minutes' | 'seconds'

export type Duration = {
    timeValue: number
    unit: SmallTimeUnit
}

export enum EventDefinitionType {
    Event = 'event',
    EventInternal = 'event_internal',
    EventCustom = 'event_custom',
    EventPostHog = 'event_posthog',
}

export const INTEGRATION_KINDS = [
    'slack',
    'salesforce',
    'hubspot',
    'google-pubsub',
    'google-cloud-service-account',
    'google-cloud-storage',
    'google-ads',
    'google-analytics',
    'google-calendar',
    'google-search-console',
    'google-sheets',
    'linkedin-ads',
    'snapchat',
    'stripe',
    'intercom',
    'email',
    'twilio',
    'linear',
    'github',
    'gitlab',
    'helpscout',
    'meta-ads',
    'instagram',
    'clickup',
    'reddit-ads',
    'databricks',
    'tiktok-ads',
    'bing-ads',
    'vercel',
    'azure-blob',
    'firebase',
    'jira',
    'pinterest-ads',
    'pardot',
    'customerio-app',
    'customerio-webhook',
    'customerio-track',
    'apns',
    'apple-ads',
    'postgresql',
    'aws-s3',
    'aws-redshift',
    's3-compatible',
    'snowflake',
    'youtube-analytics',
    'twitter-ads',
] as const

export type IntegrationKind = (typeof INTEGRATION_KINDS)[number]

// Canonical bot scopes PostHog requests during the Slack OAuth install flow. Single source of
// truth for both the frontend (app-manifest snippet + IntegrationView scope-mismatch banner)
// and the backend (`POSTHOG_SLACK_SCOPE` in posthog/models/integration/oauth.py, via posthog/schema.py).
// Widening this list will surface the "Required scopes are missing" banner for any workspace
// authorized before the change.
//
// Declared as an enum (not `as const` + derived type) because ts-json-schema-generator prunes
// type-alias-only re-exports that aren't referenced as a property type — see ChartDisplayCategory
// in schema-general.ts for the equivalent value+type re-export pattern that flows cleanly to
// `class SlackIntegrationScope(StrEnum)` in posthog/schema.py.
export enum SlackIntegrationScope {
    APP_MENTIONS_READ = 'app_mentions:read',
    ASSISTANT_WRITE = 'assistant:write',
    CANVASES_WRITE = 'canvases:write',
    CHANNELS_HISTORY = 'channels:history',
    CHANNELS_MANAGE = 'channels:manage',
    CHANNELS_READ = 'channels:read',
    CHAT_WRITE = 'chat:write',
    CHAT_WRITE_CUSTOMIZE = 'chat:write.customize',
    COMMANDS = 'commands',
    FILES_READ = 'files:read',
    FILES_WRITE = 'files:write',
    GROUPS_HISTORY = 'groups:history',
    GROUPS_READ = 'groups:read',
    IM_HISTORY = 'im:history',
    LINKS_READ = 'links:read',
    LINKS_WRITE = 'links:write',
    MPIM_HISTORY = 'mpim:history',
    MPIM_READ = 'mpim:read',
    REACTIONS_READ = 'reactions:read',
    REACTIONS_WRITE = 'reactions:write',
    TEAM_READ = 'team:read',
    USERS_READ = 'users:read',
    USERS_READ_EMAIL = 'users:read.email',
}

export const SLACK_INTEGRATION_SCOPES = Object.values(SlackIntegrationScope)

// Scopes that wait on Slack app review. Only DEV and local development request them, because the
// US and EU apps reject them with `invalid_scope`. Move a scope to SlackIntegrationScope when Slack approves it.
/** @schemaEnum */
export enum SlackIntegrationScopeInReview {
    CANVASES_READ = 'canvases:read',
    CHANNELS_JOIN = 'channels:join',
}

export const SLACK_INTEGRATION_SCOPES_IN_REVIEW = Object.values(SlackIntegrationScopeInReview)

export function slackRequestedScopes(includeInReview: boolean): string[] {
    return includeInReview
        ? [...SLACK_INTEGRATION_SCOPES, ...SLACK_INTEGRATION_SCOPES_IN_REVIEW]
        : [...SLACK_INTEGRATION_SCOPES]
}

export interface IntegrationType {
    id: number
    kind: IntegrationKind
    display_name: string
    icon_url: string
    config: any
    created_by?: UserBasicType | null
    created_at: string
    errors?: string
    files_write_requestable?: IntegrationConfigApi['files_write_requestable']
    /** GitHub only. When false, disconnecting also uninstalls the App from GitHub. */
    installation_shared?: IntegrationConfigApi['installation_shared']
    /** GitHub only. `unavailable` once the App was removed or suspended on GitHub. */
    installation_status?: IntegrationConfigApi['installation_status']
    /** Linear only. True when the workspace last authorized PostHog before the app had webhooks. */
    needs_webhook_reconnect?: IntegrationConfigApi['needs_webhook_reconnect']
}

export interface EmailIntegrationDomainGroupedType {
    domain: string
    integrations: IntegrationType[]
}

export interface SlackChannelType {
    id: string
    // Absent for private channels the bot can't access (is_private_without_access).
    name?: string
    is_private: boolean
    is_ext_shared: boolean
    is_member: boolean
    is_private_without_access?: boolean
}

export interface TwilioPhoneNumberType {
    sid: string
    phone_number: string
    friendly_name: string
}
export interface LinearTeamType {
    id: string
    name: string
}

export interface JiraProjectType {
    id: string
    key: string
    name: string
}

export interface SharePasswordType {
    id: string
    created_at: string
    note: string
    created_by_email: string
    is_active: boolean
    password?: string
}

export interface SharingConfigurationType {
    has_relevant_access_controls?: SharingConfigurationApi['has_relevant_access_controls']
    enabled: boolean
    access_token: string
    created_at: string
    password_required: boolean
    settings?: SharingConfigurationSettings
    share_passwords?: SharePasswordType[]
    user_access_level?: AccessControlLevel
}

export enum ExporterFormat {
    PNG = 'image/png',
    CSV = 'text/csv',
    PDF = 'application/pdf',
    JSON = 'application/json',
    XLSX = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    WEBM = 'video/webm',
    MP4 = 'video/mp4',
    GIF = 'image/gif',
    HCL = 'text/hcl',
    MARKDOWN = 'text/markdown',
    JSONL = 'application/x-ndjson',
}

/** Exporting directly from the browser to a file */
export type LocalExportContext = {
    localData: string
    filename: string
    mediaType?: ExporterFormat
}

export type OnlineExportContext = {
    method?: string
    path: string
    query?: any
    body?: any
    filename?: string
}

export type QueryExportContext = {
    source: Record<string, any>
    filename?: string
}

export interface ReplayExportContext {
    session_recording_id: string
    timestamp?: number
    css_selector?: string
    width?: number
    height?: number
    filename?: string
    duration?: number
    mode?: SessionRecordingPlayerMode
    skip_inactivity?: boolean
}

export interface HeatmapExportContext {
    heatmap_url: string
    heatmap_data_url?: string
    heatmap_type?: HeatmapType
    filename?: string
    heatmap_filters?: HeatmapFilters
    heatmap_color_palette?: string | null
    heatmap_fixed_position_mode?: HeatmapFixedPositionMode
    common_filters?: CommonFilters
    width?: number
    height?: number
}

export type ExportContext = (
    | OnlineExportContext
    | LocalExportContext
    | QueryExportContext
    | ReplayExportContext
    | HeatmapExportContext
) & {
    row_limit?: number // Some exports have different row limits, e.g. logs
    columns?: string[]
    variables_override?: Record<string, any>
}

export interface ExportedAssetType {
    id: number
    export_format: ExporterFormat
    dashboard?: number
    insight?: number
    export_context?: ExportContext
    has_content: boolean
    filename: string
    created_at: string
    expires_after?: string
    exception?: string
    user_access_level?: AccessControlLevel
}

export enum FeatureFlagReleaseType {
    ReleaseToggle = 'Release toggle',
    Variants = 'Multiple variants',
}

export interface MediaUploadResponse {
    id: string
    image_location: string
    name: string
}

export enum Resource {
    FEATURE_FLAGS = 'feature flags',
}

export interface RoleType {
    id: string
    name: string
    members: RoleMemberType[]
    created_at: string
    created_by: UserBasicType | null
}

export interface RoleMemberType {
    id: string
    user: UserBaseType
    role_id: string
    joined_at: string
    updated_at: string
    user_uuid: string
}

// Every grantable scope object. `hogli build:openapi` generates the enum from posthog/scopes.py,
// through the `resource` choice fields of the access control serializers.
export type APIScopeObject = ScopeObjectEnumApi

export type APIScopeAction = 'read' | 'write'

export type APIScope = {
    key: APIScopeObject
    objectName: string
    objectPlural: string
    info?: string | JSX.Element
    disabledActions?: APIScopeAction[]
    disabledWhenProjectScoped?: boolean
    description?: string
    warnings?: Partial<Record<APIScopeAction, string | JSX.Element>>
}

export type APIScopePreset = {
    value: string
    label: string
    scopes: string[]
    isCloudOnly?: boolean
}

export enum AccessControlLevel {
    None = 'none',
    Member = 'member',
    Admin = 'admin',
    Viewer = 'viewer',
    Editor = 'editor',
    Manager = 'manager',
}

export interface AccessControlTypeBase {
    created_by: UserBasicType | null
    created_at: string
    updated_at: string
    resource: APIScopeObject
    access_level: AccessControlLevel | null
    organization_member?: OrganizationMemberType['id'] | null
    role?: RoleType['id'] | null
}

export interface AccessControlTypeProject extends AccessControlTypeBase {}

export interface AccessControlTypeMember extends AccessControlTypeBase {
    organization_member: OrganizationMemberType['id']
}

export interface AccessControlTypeOrganizationAdmins extends AccessControlTypeBase {
    organization_admin_members: OrganizationMemberType['id'][]
}

export interface AccessControlTypeRole extends AccessControlTypeBase {
    role: RoleType['id']
}

export type AccessControlType = AccessControlTypeProject | AccessControlTypeMember | AccessControlTypeRole

export type AccessControlUpdateType = Pick<AccessControlType, 'access_level' | 'organization_member' | 'role'> & {
    resource?: AccessControlType['resource']
}

/** Which rule supplied an inherited access level — mirrors `ResolvedAccess.source` on the backend. */
export type InheritedAccessSource =
    | 'object'
    | 'parent_object'
    | 'resource'
    | 'parent_resource'
    | 'system_default'
    | 'org_admin'
    | 'creator'
    | 'org_membership'

/** What an object falls back to while it carries no override of its own, with the rule that
 * decided it, resolved by the same walker that enforces access. */
export type InheritedAccessType = {
    access_level: AccessControlLevel
    source: InheritedAccessSource
    source_subject: 'member' | 'role' | 'default' | null
    source_resource: APIScopeObject
    source_resource_id: string | null
    /** Human name of the parent object the level comes through (e.g. a table's source type). */
    source_display_name: string | null
}

export type AccessControlResponseType = {
    access_controls: AccessControlType[]
    available_access_levels: AccessControlLevel[]
    user_access_level: AccessControlLevel
    default_access_level: AccessControlLevel
    minimum_access_level?: AccessControlLevel
    user_can_edit_access_levels: boolean
    /** The level and rule that apply while the object carries no override of its own; null when
     * nothing sits above the object (e.g. a project). */
    inherited_access?: InheritedAccessType | null
}

export interface EffectiveAccessControlEntry {
    /** The subject's own stored rule, if any — what the settings UI edits. */
    access_level: AccessControlLevel | null
    /** What the subject actually gets, as enforced. */
    effective_access_level: AccessControlLevel | null
    /** What the subject would get if their own rule were removed, with the rule that decides
     * it — resolved by the same walker that enforces access. Null only when nothing sits above
     * the object's own default (a project's default). */
    inherited_access: Omit<InheritedAccessType, 'source_display_name'> | null
    minimum: AccessControlLevel
    maximum: AccessControlLevel
}

export interface ObjectRuleResource {
    resource: APIScopeObject
    available_access_levels: AccessControlLevel[]
    /** Levels below this are rejected by the backend, so the pickers offer them disabled. */
    minimum_access_level: AccessControlLevel
}

export interface AccessControlDefaultsResponse {
    available_project_levels: AccessControlLevel[]
    available_resource_levels: AccessControlLevel[]
    can_edit: boolean
    is_managed_by_terraform: boolean
    project_access_level: AccessControlLevel
    resource_access_levels: Record<string, EffectiveAccessControlEntry>
    /** Resources supporting object-level rules, derived server-side from viewset registration,
     * each with the levels a rule on it accepts. */
    object_rule_resources: ObjectRuleResource[]
}

export interface AccessControlRolesResponse {
    available_project_levels: AccessControlLevel[]
    available_resource_levels: AccessControlLevel[]
    can_edit: boolean
    results: {
        role_id: RoleType['id']
        role_name: string
        project: EffectiveAccessControlEntry
        resources: Record<string, EffectiveAccessControlEntry>
    }[]
}

export interface AccessControlMembersResponse {
    available_project_levels: AccessControlLevel[]
    available_resource_levels: AccessControlLevel[]
    can_edit: boolean
    results: {
        organization_membership_id: OrganizationMemberType['id']
        user: { uuid: string; first_name: string; email: string }
        organization_level: number
        project: EffectiveAccessControlEntry
        resources: Record<string, EffectiveAccessControlEntry>
    }[]
}

export type JsonType = string | number | boolean | null | { [key: string]: JsonType } | Array<JsonType>

export type PromptButtonType = 'primary' | 'secondary'
export type PromptType = 'modal' | 'popup'

export type PromptPayload = {
    title: string
    body: string
    type: PromptType
    image?: string
    url_match?: string
    primaryButtonText?: string
    secondaryButtonText?: string
    primaryButtonURL?: string
}

export type PromptFlag = {
    flag: string
    payload: PromptPayload
    showingPrompt: boolean
    locationCSS?: Partial<CSSStyleDeclaration>
    tooltipCSS?: Partial<CSSStyleDeclaration>
}

// Should be kept in sync with "posthog/models/activity_logging/activity_log.py"
export enum ActivityScope {
    DATA_QUALITY_CHECK_SCHEDULE = 'DataQualityCheckSchedule',
    DEV_GATEWAY_TOKEN = 'DevGatewayToken',
    ACTION = 'Action',
    ACCOUNT_VIEW = 'AccountView',
    ALERT_CONFIGURATION = 'AlertConfiguration',
    ANNOTATION = 'Annotation',
    BATCH_EXPORT = 'BatchExport',
    BATCH_IMPORT = 'BatchImport',
    BILLING = 'Billing',
    EXPORTED_ASSET = 'ExportedAsset',
    FEATURE_FLAG = 'FeatureFlag',
    PERSON = 'Person',
    PERSONAL_API_KEY = 'PersonalAPIKey',
    PROJECT_SECRET_API_KEY = 'ProjectSecretAPIKey',
    GROUP = 'Group',
    INSIGHT = 'Insight',
    PLUGIN = 'Plugin',
    PLUGIN_CONFIG = 'PluginConfig',
    HOG_FUNCTION = 'HogFunction',
    HOG_FLOW = 'HogFlow',
    DATA_MANAGEMENT = 'DataManagement',
    EVENT_DEFINITION = 'EventDefinition',
    PROPERTY_DEFINITION = 'PropertyDefinition',
    NOTEBOOK = 'Notebook',
    GENERATED_WIDGET = 'GeneratedWidget',
    CANVAS = 'Canvas',
    DASHBOARD = 'Dashboard',
    CROSS_PROJECT_DASHBOARD = 'CrossProjectDashboard',
    REPLAY = 'Replay',
    REPLAY_SCANNER = 'ReplayScanner',
    REPLAY_OBSERVATION = 'ReplayObservation',
    VISION_ALERT_CONFIGURATION = 'VisionAlertConfiguration',
    // TODO: doh! we don't need replay and recording
    RECORDING = 'recording',
    EXPERIMENT = 'Experiment',
    SURVEY = 'Survey',
    EARLY_ACCESS_FEATURE = 'EarlyAccessFeature',
    COMMENT = 'Comment',
    COHORT = 'Cohort',
    TEAM = 'Team',
    ORGANIZATION = 'Organization',
    ORGANIZATION_MEMBERSHIP = 'OrganizationMembership',
    ORGANIZATION_INVITE = 'OrganizationInvite',
    ORGANIZATION_DOMAIN = 'OrganizationDomain',
    OAUTH_APPLICATION = 'OAuthApplication',
    WORKLOAD_TRUST_POLICY = 'WorkloadTrustPolicy',
    WORKLOAD_TRUST_POLICY_REQUEST = 'WorkloadTrustPolicyRequest',
    LEGAL_DOCUMENT = 'LegalDocument',
    ERROR_TRACKING_ISSUE = 'ErrorTrackingIssue',
    DATA_WAREHOUSE_EXPRESSION = 'DataWarehouseExpression',
    DATA_WAREHOUSE_SAVED_QUERY = 'DataWarehouseSavedQuery',
    DATA_WAREHOUSE_TABLE = 'DataWarehouseTable',
    DATA_WAREHOUSE_JOIN = 'DataWarehouseJoin',
    ACCESS_CONTROL = 'AccessControl',
    DATA_QUALITY_CHECK = 'DataQualityCheck',
    WAREHOUSE_SUGGESTION = 'WarehouseSuggestion',
    TAG = 'Tag',
    TAGGED_ITEM = 'TaggedItem',
    EVALUATION = 'Evaluation',
    EXTERNAL_DATA_SOURCE = 'ExternalDataSource',
    EXTERNAL_DATA_SCHEMA = 'ExternalDataSchema',
    ENDPOINT = 'Endpoint',
    ENDPOINT_VERSION = 'EndpointVersion',
    HEATMAP = 'Heatmap',
    USER = 'User',
    LLM_PROMPT = 'LLMPrompt',
    LLM_PROMPT_LABEL = 'LLMPromptLabel',
    LLM_SKILL = 'LLMSkill',
    LLM_TRACE = 'LLMTrace',
    LOG = 'Log',
    LOGS_ALERT_CONFIGURATION = 'LogsAlertConfiguration',
    PLATFORM_ALERT_CONFIGURATION = 'PlatformAlertConfiguration',
    PRODUCT_TOUR = 'ProductTour',
    TICKET = 'Ticket',
    TICKET_MACRO = 'TicketMacro',
    KNOWLEDGE_SOURCE = 'KnowledgeSource',
    KNOWLEDGE_LIBRARY = 'KnowledgeLibrary',
    INSTANCE_SETTING = 'InstanceSetting',
    SIGNAL_SCOUT_CONFIG = 'SignalScoutConfig',
    SIGNAL_TEAM_CONFIG = 'SignalTeamConfig',
    STAMPHOG_REPO_CONFIG = 'StamphogRepoConfig',
    REVIEW_REPOSITORY = 'ReviewRepository',
    REVIEW_PROJECT_SETTINGS = 'ReviewProjectSettings',
    REVIEW_INSTALLATION_CLAIM = 'ReviewInstallationClaim',
}

export type CommentType = {
    id: string
    content: string | null
    rich_content: JSONContent | null
    version: number
    created_at: string
    created_by: UserBasicType | null
    source_comment?: string | null
    scope: ActivityScope | string
    item_id?: string
    item_context: Record<string, any> | null
    /** only on the type to support patching for soft delete */
    deleted?: boolean
    is_task: boolean
    completed_at: string | null
    completed_by: UserBasicType | null
    /** The Slack thread this comment's discussion is mirrored to (read-only); set only on a tracked thread root. */
    slack_thread?: CommentSlackThreadRefApi | null
}

export type CommentCreationParams = { mentions?: number[]; slug?: string }

export interface DataWarehouseCredential {
    access_key: string
    access_secret: string
}
export interface DataWarehouseTable {
    /** UUID */
    id: string
    name: string
    /** Dotted name the table is queried by in HogQL (e.g. `stripe.charges`), as opposed to `name` (the storage identifier). */
    hogql_name?: string
    /** Serialized columns; omitted when the table was listed with `include_columns=false`. */
    columns?: DatabaseSchemaField[]
    format: DataWarehouseTableTypes
    created_by?: UserBasicType | null
    created_at?: string | null
    url_pattern: string
    /** Null for tables without user-provided credentials, e.g. created by a managed pipeline. */
    credential: DataWarehouseCredential | null
    external_data_source?: ExternalDataSource
    external_schema?: SimpleExternalDataSourceSchema
    /** The managed source that will import this self-managed table on its first sync, if one is linked. */
    pending_source_id?: string | null
    options?: { csv_allow_double_quotes?: boolean | null }
    user_access_level?: AccessControlLevel
}

export type DataWarehouseTableTypes = 'CSV' | 'Parquet' | 'JSON' | 'CSVWithNames'

export type DataModelingJobStatus = 'Running' | 'Completed' | 'Failed' | 'Cancelled' | 'Skipped'

export interface DataWarehouseSavedQueryRunHistory {
    status: DataModelingJobStatus
    timestamp?: string
}

export interface DataWarehouseSavedQueryDependencies {
    upstream_count: number
    downstream_count: number
}

export type DataModelingNodeType = NodeTypeEnumApi

export interface DataModelingNode {
    /** UUID */
    id: string
    name: string
    type: DataModelingNodeType
    description?: string
    description_source?: WarehouseColumnAnnotationDescriptionSourceEnumApi | null
    saved_query_id?: string
    /** UUID of the data catalog metric a metric node stands for */
    metric_id?: string | null
    lineage_issue?: LineageIssueApi | null
    origin?: 'posthog' | 'warehouse' | null
    warehouse_table_id?: string | null
    created_at: string
    updated_at: string
    upstream_count: number
    downstream_count: number
    user_tag?: string
    last_run_at?: string | null
    last_run_status?: DataModelingJobStatus
    last_run_error?: string | null
    sync_interval?: DataModelingSyncInterval
    effective_sync_interval?: DataModelingSyncInterval | null
    pinned?: boolean
    suspended?: NodeApiSuspended
    /** Set on endpoint nodes stamped at materialization enable; older nodes carry only the name */
    endpoint?: NodeEndpointApi | null
}

export interface DataModelingEdge {
    /** UUID */
    id: string
    source_id: string
    target_id: string
}

export type DataModelingSyncInterval = '15min' | '30min' | '1hour' | '6hour' | '12hour' | '24hour' | '7day' | '30day'

export interface DataWarehouseSavedQuery {
    /** UUID */
    id: string
    name: string
    description?: string | null
    /** Only included when fetching a single saved query, not in list responses */
    query?: HogQLQuery
    columns: DatabaseSchemaField[]
    last_run_at?: string
    sync_frequency?: string
    /** Which cadences this view's lineage allows, and what withholds the rest. Single fetches only */
    sync_frequency_bounds?: SyncFrequencyBoundsApi
    status?: string
    managed_viewset_kind: DataWarehouseManagedViewsetKind | null
    folder_id?: string | null
    folder_name?: string | null
    latest_error: string | null
    latest_history_id?: string
    is_materialized?: boolean
    /** Whether the view is set up to update incrementally. A run can still rebuild the whole table,
     * for example on its first run or after the query changes. */
    is_incremental?: boolean
    /** The view stores raw Trino SQL. Only hosted Trino can run it, and HogQL cannot reference it. */
    is_raw_managed_trino?: boolean
    /** Engine → suspension details */
    suspended?: DataWarehouseSavedQueryApiSuspended
    created_by?: UserBasicType | null
    created_at?: string
    updated_at?: DataWarehouseSavedQueryApi['updated_at']
    run_history?: DataWarehouseSavedQueryRunHistory[]
    origin?: DataWarehouseSavedQueryOrigin
    is_test?: boolean
    expires_at?: string
    user_access_level?: AccessControlLevel
    incremental?: DataWarehouseSavedQueryIncremental | null
    incremental_state?: DataWarehouseSavedQueryIncrementalState | null
    /** Whether incremental settings participated in any materialization run. */
    has_incremental_history?: boolean
}

export interface DataWarehouseSavedQueryIncremental {
    enabled: boolean
    /** Output column whose advancing value marks rows as new */
    incremental_key: string
    /** Output columns that identify a row. Must cover every GROUP BY column, and never be null */
    unique_key: string[]
    /** How far back before the last high point to re-read, for late-arriving data */
    lookback_seconds?: number
}

export interface DataWarehouseSavedQueryIncrementalState {
    watermark?: string | null
    definition_fingerprint?: string | null
    last_full_refresh_at?: string | null
    last_run_mode?: 'incremental' | 'full_refresh' | null
}

export interface DataWarehouseSavedQueryIncrementalCheck {
    eligible: boolean
    key_candidates: string[]
    /** Superset of key_candidates: identity only needs equality, so strings qualify here */
    unique_key_candidates?: string[]
    /** Coarse type per candidate (datetime, date, integer, ...). No entry: type unknown */
    key_candidate_types?: Record<string, string>
    blockers: string[]
    warnings: string[]
}

export interface DataWarehouseSavedQueryFolder {
    /** UUID */
    id: string
    name: string
    created_at?: string
    view_count?: number
}

export interface DataWarehouseSavedQueryDraft {
    id: string
    query: HogQLQuery
    saved_query_id?: string
    created_at: string
    updated_at: string
    name: string
    edited_history_id?: string
}

export interface DataWarehouseViewLink {
    id: string
    source_table_name?: string
    source_table_key?: string
    joining_table_name?: string
    joining_table_key?: string
    field_name?: string
    created_by?: UserBasicType | null
    created_at?: string | null
}

export interface DataWarehouseViewLinkValidation {
    is_valid: boolean
    msg: string | null
    hogql: string | null
    columns: string[]
    results: any[]
    total_rows: number | null
    matched_rows: number | null
    match_rate: number | null
}

export interface QueryTabState {
    id: string
    state: Record<string, any>
}

export enum DataWarehouseSettingsTab {
    Managed = 'managed',
    SelfManaged = 'self-managed',
}

export const manualLinkSources = ['aws', 'google-cloud', 'cloudflare-r2', 'azure'] as const

export type ManualLinkSourceType = (typeof manualLinkSources)[number]

/**
 * A warehouse source's catalog key, e.g. 'Stripe'. A source plugin can name itself with any key, so this
 * is a plain string and not a union of the known keys. The wizard endpoint lists the keys that exist.
 */
export type ExternalDataSourceType = string

export interface ExternalDataSourceRevenueAnalyticsConfig {
    enabled: boolean
    include_invoiceless_charges: boolean
}

export interface ExternalDataSourceCreatePayload {
    source_type: ExternalDataSourceType
    prefix?: string
    description?: string
    access_method?: 'warehouse' | 'direct'
    direct_query_enabled?: boolean
    created_via: 'web' | 'api' | 'mcp'
    payload: Record<string, any>
    /** Destinations every table on the source writes to. Set at creation so the opening sync carries them. */
    destination_ids?: string[]
}

/** Response of `POST warehouse_tables/upload_file` — the stored file a self-managed table is built from. */
export interface WarehouseTableFileUpload {
    upload_id: string
    filename: string
    file_format: string
    size_bytes: number
}

export interface ExternalDataSourceConnectionMetadata {
    database?: string | null
    version?: string | null
    engine?: 'duckdb' | 'postgres' | 'mysql' | null
    function_source?: string | null
    available_functions?: string[]
}

export interface ExternalDataSource {
    id: string
    source_id: string
    connection_id: string
    status: ExternalDataJobStatus
    source_type: ExternalDataSourceType
    prefix: string | null
    description: string | null
    created_by?: string | null
    created_at?: string | null
    access_method?: 'warehouse' | 'direct'
    direct_query_enabled?: boolean
    auto_sync_new_schemas?: boolean
    auto_sync_schema_patterns?: string[] | null
    created_via: 'web' | 'api' | 'mcp' | 'wizard' | null
    engine?: 'duckdb' | 'postgres' | 'mysql' | 'snowflake' | 'redshift' | null
    latest_error: string | null
    last_run_at?: Dayjs
    schemas: ExternalDataSourceSchema[]
    /** The name of the file a file upload source imports. */
    file_name?: string | null
    sync_frequency: DataWarehouseSyncInterval
    job_inputs: Record<string, any>
    revenue_analytics_config: ExternalDataSourceRevenueAnalyticsConfig
    user_access_level: AccessControlLevel
    supports_webhooks?: boolean
    /** Whether a table of this source uses webhook sync, but the source has no enabled webhook. */
    webhook_not_registered?: boolean
    supports_column_selection?: boolean
    api_version?: string | null
    api_version_deprecation?: ExternalDataSourceApiVersionDeprecation | null
    connection_warning?: string | null
}

export interface ExternalDataSourceApiVersionDeprecation {
    /** The deprecated vendor API version this source is pinned to */
    version: string
    /** ISO date the vendor stops serving this version; null if not announced */
    sunset_at: string | null
    /** The source type's current default vendor API version — the migration target */
    default_version: string
}

export interface WebhookExternalStatus {
    exists: boolean
    url?: string
    enabled_events?: string[]
    status?: string
    description?: string
    created_at?: string
    error?: string
}

export type WebhookInputValue = { secret: true } | { value: unknown }

export interface WebhookInfo {
    supports_webhooks: boolean
    exists: boolean
    hog_function?: {
        id: string
        name: string
        enabled: boolean
        created_at: string
        status: { state: number; tokens: number }
    }
    webhook_url?: string
    schema_mapping?: Record<string, string>
    inputs?: Record<string, WebhookInputValue>
    // Required webhook field names with no value yet. Deliveries are dropped while any is missing.
    missing_inputs?: string[]
    external_status?: WebhookExternalStatus | null
    // Desired provider events not yet on the webhook (manual setup, or created before a new table).
    missing_events?: string[]
    // Set when the connection's credentials can never create the webhook, so only manual setup is
    // left. Null means "not known to be blocked", which is the answer for any credential whose
    // grants can't be introspected.
    auto_creation_blocked_reason?: string | null
}

export interface DataModelingJob {
    id: string
    saved_query_id: string
    status: DataModelingJobStatus
    /** full_refresh: rows_materialized is the whole table. incremental: only the rows synced. Null: unknown (old run) */
    run_mode?: 'full_refresh' | 'incremental' | null
    rows_materialized: number
    rows_expected: number | null
    error: string | null
    created_at: string
    last_run_at: string
    /** When the job row last changed; for finished jobs this approximates when the run ended. */
    updated_at?: string
    workflow_id: string
    workflow_run_id: string | null
}

export interface SimpleExternalDataSourceSchema {
    id: string
    name: string
    label: string | null
    should_sync: boolean
    last_synced_at?: Dayjs
    sync_type?: 'full_refresh' | 'incremental' | 'append' | 'webhook' | 'cdc' | 'xmin' | null
}

export interface AvailableColumn {
    label: string
    field: string
    type: string
    nullable: boolean
}

/** The comparison operators a row filter may use. Mirrors the backend allowlist. */
export type RowFilterOperator = '>' | '>=' | '<' | '<=' | '=' | '!=' | 'IN' | 'NOT IN'

/** A `{column, operator, value}` predicate ANDed onto a schema's source query. For `IN` / `NOT IN`, `value` is a comma-separated string. */
export interface RowFilter {
    column: string
    operator: RowFilterOperator
    value: string | number | boolean
}

export type SchemaIncrementalFieldsResponse = {
    incremental_fields: IncrementalField[]
    incremental_available: boolean
    append_available: boolean
    full_refresh_available: boolean
    supports_webhooks: boolean
    available_columns: AvailableColumn[]
    detected_primary_keys: string[] | null
    primary_key_detection_supported?: boolean
    cdc_available?: boolean
    xmin_available?: boolean
}

// numeric is snowflake specific and objectid is mongodb specific
export type IncrementalFieldType = 'integer' | 'numeric' | 'datetime' | 'date' | 'timestamp' | 'objectid'

export interface IncrementalField {
    label: string // the field name shown in the UI
    type: IncrementalFieldType // the field type shown in the UI
    field: string // the actual database field name
    field_type: IncrementalFieldType // the actual database field type
    nullable?: boolean // whether the field allows null values
    is_indexed?: boolean // leading column of an index/clustering/sort/partition key on the source
}

export interface ExternalDataSourceSyncSchema {
    table: string
    label?: string | null
    rows?: number | null
    should_sync: boolean
    sync_time_of_day: string | null
    incremental_field: string | null
    incremental_field_type: string | null
    /** Seconds subtracted from the incremental watermark at sync time to re-read a rolling overlap
     *  window (catches late/backdated rows). Timestamp/date incremental fields only. */
    incremental_field_lookback_seconds?: number | null
    sync_type: 'full_refresh' | 'incremental' | 'append' | 'webhook' | 'cdc' | 'xmin' | null
    incremental_fields: IncrementalField[]
    incremental_available: boolean
    append_available: boolean
    cdc_available?: boolean
    xmin_available?: boolean
    cdc_table_mode?: 'consolidated' | 'cdc_only' | 'both'
    supports_webhooks: boolean
    /** True when the resource has no API list endpoint and can only be populated via webhooks
     *  (e.g. Stripe Discount). The picker should hide non-webhook sync methods. */
    webhook_only?: boolean
    /** True when only a full refresh keeps the table equal to the origin (e.g. file imports), so the
     *  wizard defaults it to `full_refresh` even though incremental or append is available. */
    prefers_full_refresh?: boolean
    description?: string | null
    should_sync_default: boolean
    primary_key_columns: string[] | null
    available_columns: AvailableColumn[]
    detected_primary_keys: string[] | null
    primary_key_detection_supported?: boolean
    /**
     * For sources that gate read access by scope (e.g. Stripe restricted API keys), the
     * reason this endpoint is currently unreachable. `null`/undefined = endpoint is
     * available. The UI should disable selection and surface this string when set.
     */
    permission_error?: string | null
    /**
     * Advisory warning when row-level security is active for the sync role on this table:
     * the sync may read fewer rows than the table contains, and the gap can't be measured.
     * `null`/undefined = no warning. Unlike `permission_error` this does NOT block selection.
     */
    rls_warning?: string | null
    /**
     * User-selected source columns to sync. `null`/undefined = sync all columns.
     * PK columns and the active incremental field are always retained server-side.
     */
    enabled_columns?: string[] | null
    /** Source columns whose values are replaced with a one-way hash at sync time. */
    masked_columns?: string[] | null
    /**
     * Predicates ANDed onto the source query so only matching rows sync.
     * `null`/undefined/empty = sync all rows.
     */
    row_filters?: RowFilter[] | null
}

/** Why the last sync run could not merge rows on a table's primary key. */
export type IncrementalSyncBlockedReason = IncrementalSyncBlockedReasonEnumApi

export interface ExternalDataSourceSchema extends SimpleExternalDataSourceSchema {
    table?: SimpleDataWarehouseTable
    /** The live table the schema syncs into, also before its first sync when the schema already names one. */
    table_id?: string | null
    /** The schema is linked to a self-managed table that its first sync will import. */
    pending_self_managed_table?: boolean
    incremental: boolean
    sync_type: 'incremental' | 'full_refresh' | 'append' | 'webhook' | 'cdc' | 'xmin' | null
    sync_time_of_day: string | null
    status?: ExternalDataSchemaStatus
    latest_error: string | null
    incremental_field: string | null
    incremental_field_type: string | null
    /** Seconds subtracted from the incremental watermark at sync time to re-read a rolling overlap
     *  window (catches late/backdated rows). Timestamp/date incremental fields only. */
    incremental_field_lookback_seconds?: number | null
    sync_frequency: DataWarehouseSyncInterval
    description?: string | null
    should_sync_default?: boolean
    primary_key_columns: string[] | null
    cdc_table_mode?: 'consolidated' | 'cdc_only' | 'both'
    /** The history table's name, or `null` when the table keeps no history. Older history tables end in `_cdc`. */
    history_table_name?: string | null
    /**
     * Why the last sync run could not merge rows on this table's primary key, or `null` when no such
     * failure is current. A later run that succeeds, or fails for another reason, clears it.
     */
    incremental_sync_blocked?: IncrementalSyncBlockedReason | null
    /** Whether this table uses webhook sync, but its source has no enabled webhook. */
    webhook_not_registered?: boolean
    /**
     * User-selected source columns to sync. `null` means "sync all columns".
     * Primary-key + active incremental columns are always retained even if not listed.
     */
    enabled_columns?: string[] | null
    /** Source columns whose values are replaced with a one-way hash at sync time. */
    masked_columns?: string[] | null
    available_columns?: { name: string; data_type?: string; is_nullable?: boolean }[]
    /** Exact source identifiers are available for sources that project columns upstream. */
    source_column_metadata_available?: boolean
    /**
     * Predicates ANDed onto the source query so only matching rows sync.
     * `null` means "sync all rows". Applied on the next sync — not retroactive.
     */
    row_filters?: RowFilter[] | null
    /** Columns a row filter may use; null means any column in `available_columns`. */
    row_filter_columns?: readonly RowFilterColumnApi[] | null
    /** User-managed vendor API version override; null syncs on the source's pinned version */
    api_version?: string | null
    /** Set when this schema's version override is deprecated by the vendor */
    api_version_deprecation?: ExternalDataSourceApiVersionDeprecation | null
    /** The requesting user's effective access level for this table (inherits the source). */
    user_access_level?: AccessControlLevel
}

/** Lightweight parent-source summary embedded in the single-schema retrieve endpoint. */
export interface ExternalDataSchemaSourceSummary {
    id: string
    source_type: ExternalDataSourceType
    access_method?: ExternalDataSource['access_method']
    supports_column_selection?: boolean
    supports_row_filters?: boolean
    requires_exact_column_metadata?: boolean
    /** The name of the file a file upload source imports. */
    file_name?: string | null
    user_access_level: AccessControlLevel | null
    /** The source's effective vendor API version — what schemas without an override sync on */
    api_version?: string | null
    /** Vendor API versions the source type supports — the schema override picker's options */
    supported_api_versions?: string[]
}

export interface ExternalDataSchemaWithSource extends ExternalDataSourceSchema {
    /** Populated only on the single-schema retrieve endpoint; `null` when serialized elsewhere. */
    source: ExternalDataSchemaSourceSummary | null
}

export enum ExternalDataSchemaStatus {
    Running = 'Running',
    Completed = 'Completed',
    Failed = 'Failed',
    Paused = 'Paused',
    Cancelled = 'Cancelled',
}

export enum ExternalDataJobStatus {
    Running = 'Running',
    Completed = 'Completed',
    Failed = 'Failed',
    BillingLimits = 'Billing limits',
    BillingLimitTooLow = 'Billing limit too low',
}

export interface ExternalDataJob {
    id: string
    created_at: string
    finished_at: string
    status: ExternalDataJobStatus
    schema: SimpleExternalDataSourceSchema
    rows_synced: number
    latest_error: string
    workflow_run_id?: string
    /**
     * For CDC syncs with `cdc_table_mode='both'`, distinguishes the two ExternalDataJob rows
     * produced for the same schema: `incremental_merge` (consolidated table) vs `scd2_append`
     * (cdc-only history table). `null` for non-CDC syncs.
     */
    cdc_write_mode?: 'incremental_merge' | 'scd2_append' | null
    /**
     * Whether the rows synced by this job count toward billing. `false` for system-initiated
     * runs the customer isn't charged for. `null` on legacy rows and means billable.
     */
    billable?: boolean | null
    /**
     * Destinations this run delivered to, snapshotted when it started. Empty on runs that predate
     * destinations, which wrote to the PostHog warehouse alone. `rows_synced` counts the rows read
     * from the source once, not once per destination.
     */
    destination_ids?: string[]
}

export interface SimpleDataWarehouseTable {
    id: string
    name: string
    /** Dotted name the table is queried by in HogQL (e.g. `googleanalytics.devices`). */
    hogql_name?: string
    columns: DatabaseSchemaField[]
    row_count: number
}

// Credentials live on the linked `aws-s3` integration, not in the config.
export type BatchExportServiceAwsS3 = {
    type: 'AwsS3'
    integration: number
    config: {
        bucket_name: string
        region: string
        prefix: string
        exclude_events: string[]
        include_events: string[]
        compression: string | null
        encryption: string | null
        kms_key_id: string | null
        file_format: string
        max_file_size_mb: number | null
    }
}

// Credentials and the provider endpoint URL live on the linked `s3-compatible` integration.
export type BatchExportServiceS3Compatible = {
    type: 'S3Compatible'
    integration: number
    config: {
        bucket_name: string
        region: string
        prefix: string
        exclude_events: string[]
        include_events: string[]
        compression: string | null
        use_virtual_style_addressing: boolean
        file_format: string
        max_file_size_mb: number | null
    }
}

export type BatchExportServicePostgres = {
    type: 'Postgres'
    integration?: number
    config: {
        user?: string
        password?: string
        host?: string
        port?: number
        database: string
        schema: string
        table_name: string
        has_self_signed_cert: boolean
        exclude_events: string[]
        include_events: string[]
    }
}

// Credentials live on the linked `snowflake` integration, not in the config.
export type BatchExportServiceSnowflake = {
    type: 'Snowflake'
    integration: number
    config: {
        database: string
        warehouse: string
        schema: string
        table_name: string
        role: string | null
        exclude_events: string[]
        include_events: string[]
    }
}

export type BatchExportServiceBigQuery = {
    type: 'BigQuery'
    integration?: number
    config: {
        dataset_id: string
        table_id: string
        exclude_events: string[]
        include_events: string[]
        use_json_type: boolean
    }
}

export type BatchExportServiceHTTP = {
    type: 'HTTP'
    config: {
        url: string
        token: string
        exclude_events: string[]
        include_events: string[]
    }
}

export type BatchExportServiceRedshift = {
    type: 'Redshift'
    // Credentials live on the linked `aws-redshift` integration. Exports created before integrations
    // keep their inline user/password.
    integration?: number
    config: {
        user: string
        password: string
        host: string
        port: number
        database: string
        schema: string
        table_name: string
        properties_data_type: 'varchar' | 'super'
        mode: 'COPY' | 'INSERT'
        // Form-only: derived from the shape of copy_inputs.authorization, never sent to the API.
        authorization_mode: 'SameConnection' | 'DifferentConnection' | 'IAMRole'
        copy_inputs: BatchExportServiceRedshiftCopyInputs | null
        exclude_events: string[]
        include_events: string[]
    }
}

// The two COPY credentials can each reference an `aws-s3` integration by id instead of holding
// inline keys. `authorization` additionally accepts the ARN of a role attached to the cluster.
export type BatchExportServiceRedshiftCopyInputs = {
    s3_bucket: string
    s3_key_prefix: string
    region_name: string
    bucket_credentials: number | AWSCredentials
    authorization: number | string | AWSCredentials
}

export type AWSCredentials = {
    aws_access_key_id: string
    aws_secret_access_key: string
}

export type BatchExportServiceDatabricks = {
    type: 'Databricks'
    integration: number
    config: {
        http_path: string
        catalog: string
        schema: string
        table_name: string
        use_variant_type: boolean
        exclude_events: string[]
        include_events: string[]
    }
}

export type BatchExportServiceAzureBlob = {
    type: 'AzureBlob'
    integration: number
    config: {
        container_name: string
        prefix: string
        compression: string | null
        file_format: string
        max_file_size_mb: number | null
        exclude_events: string[]
        include_events: string[]
    }
}

// When adding a new option here also add a icon for it to
// frontend/public/services/
// and update RenderBatchExportIcon
export const BATCH_EXPORT_SERVICE_NAMES: BatchExportService['type'][] = [
    'AwsS3',
    'S3Compatible',
    'Snowflake',
    'Postgres',
    'BigQuery',
    'Redshift',
    'HTTP',
    'Databricks',
    'AzureBlob',
]
export type BatchExportService =
    | BatchExportServiceAwsS3
    | BatchExportServiceS3Compatible
    | BatchExportServiceSnowflake
    | BatchExportServicePostgres
    | BatchExportServiceBigQuery
    | BatchExportServiceRedshift
    | BatchExportServiceHTTP
    | BatchExportServiceDatabricks
    | BatchExportServiceAzureBlob

export type BatchExportInterval = 'hour' | 'day' | 'week' | 'every 5 minutes' | 'every 15 minutes'

export type DataWarehouseSyncInterval =
    | '1min'
    | '5min'
    | '15min'
    | '30min'
    | '1hour'
    | '6hour'
    | '12hour'
    | '24hour'
    | '7day'
    | '30day'
export type OrNever = 'never'

export type BatchExportConfiguration = {
    id: string
    team_id: number
    name: string
    destination: BatchExportService
    interval: BatchExportInterval
    timezone: string | null
    offset_day: number | null
    offset_hour: number | null
    created_at: string
    start_at: string | null
    end_at: string | null
    paused: boolean
    model: string
    hogql_query?: BatchExportApi['hogql_query']
    hogql_modifiers?: BatchExportApi['hogql_modifiers']
    filters: AnyPropertyFilter[]
    latest_runs?: BatchExportRun[]
}

export type BatchExportConfigurationTestStepStatus = 'Passed' | 'Failed' | 'Skipped'

export type BatchExportConfigurationTestStepResult = {
    status: BatchExportConfigurationTestStepStatus
    message: string
}

export type BatchExportConfigurationTestStep = {
    name: string
    description: string
    result: BatchExportConfigurationTestStepResult | null
}

export type BatchExportConfigurationTest = {
    steps: BatchExportConfigurationTestStep[]
}

export type RawBatchExportRun = {
    id: string
    status:
        | 'Cancelled'
        | 'Completed'
        | 'ContinuedAsNew'
        | 'Failed'
        | 'FailedRetryable'
        | 'FailedBilling'
        | 'Terminated'
        | 'TimedOut'
        | 'Running'
        | 'Starting'
    created_at: string
    data_interval_start?: string
    data_interval_end: string
    last_updated_at?: string
    records_completed?: number
    records_failed?: number
    bytes_exported?: number
    latest_error?: string | null
}

export type BatchExportRun = {
    id: string
    status:
        | 'Cancelled'
        | 'Completed'
        | 'ContinuedAsNew'
        | 'Failed'
        | 'FailedRetryable'
        | 'FailedBilling'
        | 'Terminated'
        | 'TimedOut'
        | 'Running'
        | 'Starting'
    created_at: Dayjs
    data_interval_start?: Dayjs
    data_interval_end: Dayjs
    last_updated_at?: Dayjs
    records_completed?: number
    records_failed?: number
    bytes_exported?: number
    latest_error?: string | null
}

export type GroupedBatchExportRuns = {
    last_run_at: Dayjs
    data_interval_start: Dayjs
    data_interval_end: Dayjs
    runs: BatchExportRun[]
}

export type BatchExportBackfillProgress = {
    total_runs?: number
    finished_runs?: number
    progress?: number
}

export type RawBatchExportBackfill = {
    id: string
    status:
        | 'Cancelled'
        | 'Completed'
        | 'ContinuedAsNew'
        | 'Failed'
        | 'FailedRetryable'
        | 'Terminated'
        | 'TimedOut'
        | 'Running'
        | 'Starting'
    created_at: string
    finished_at?: string
    start_at?: string
    end_at?: string
    last_updated_at?: string
    total_records_count?: number
    progress?: BatchExportBackfillProgress
}

export type BatchExportBackfill = {
    id: string
    status:
        | 'Cancelled'
        | 'Completed'
        | 'ContinuedAsNew'
        | 'Failed'
        | 'FailedRetryable'
        | 'Terminated'
        | 'TimedOut'
        | 'Running'
        | 'Starting'
    created_at?: Dayjs
    finished_at?: Dayjs
    start_at?: Dayjs
    end_at?: Dayjs
    last_updated_at?: Dayjs
    total_records_count?: number
    progress?: BatchExportBackfillProgress
}

export type SDK = {
    name: string
    key: string
    recommended?: boolean
    tags: SDKTag[]
    searchTerms?: string[]
    image:
        | string
        | JSX.Element
        // storybook handles require() differently, so we need to support both
        | {
              default: string
          }
    docsLink: string
}

export enum SDKKey {
    ANDROID = 'android',
    ANGULAR = 'angular',
    ANTHROPIC = 'anthropic',
    ASTRO = 'astro',
    AUTOGEN = 'autogen',
    AWS_BEDROCK = 'aws_bedrock',
    AZURE_OPENAI = 'azure_openai',
    API = 'api',
    BUBBLE = 'bubble',
    CEREBRAS = 'cerebras',
    CLOUDFLARE_AI_GATEWAY = 'cloudflare_ai_gateway',
    COHERE = 'cohere',
    CONVEX = 'convex',
    CREWAI = 'crewai',
    DJANGO = 'django',
    DEDALUS = 'dedalus',
    DEEPSEEK = 'deepseek',
    DOCUSAURUS = 'docusaurus',
    DOTNET = 'dotnet',
    DSPY = 'dspy',
    ELIXIR = 'elixir',
    EVE = 'eve',
    FRAMER = 'framer',
    FIREWORKS_AI = 'fireworks_ai',
    FLUTTER = 'flutter',
    GATSBY = 'gatsby',
    GO = 'go',
    GOOGLE_ADK = 'google_adk',
    GOOGLE_GEMINI = 'google_gemini',
    GOOGLE_TAG_MANAGER = 'google_tag_manager',
    GROQ = 'groq',
    HELICONE = 'helicone',
    HUGGING_FACE = 'hugging_face',
    INSTRUCTOR = 'instructor',
    IOS = 'ios',
    JAVA = 'java',
    JS_WEB = 'javascript_web',
    KMP = 'kmp',
    LARAVEL = 'laravel',
    LANGCHAIN = 'langchain',
    LANGGRAPH = 'langgraph',
    LANGFUSE = 'langfuse',
    LITELLM = 'litellm',
    LLAMAINDEX = 'llamaindex',
    MANUAL_CAPTURE = 'manual_capture',
    MASTRA = 'mastra',
    MIRASCOPE = 'mirascope',
    MISTRAL = 'mistral',
    MOENGAGE = 'moengage',
    N8N = 'n8n',
    NEXT_JS = 'nextjs',
    NODE_JS = 'nodejs',
    NUXT_JS = 'nuxtjs',
    NUXT_JS_36 = 'nuxtjs_36',
    OLLAMA = 'ollama',
    OPENAI = 'openai',
    OPENAI_AGENTS = 'openai_agents',
    OPENROUTER = 'openrouter',
    OPENTELEMETRY = 'opentelemetry',
    PERPLEXITY = 'perplexity',
    PHP = 'php',
    PORTKEY = 'portkey',
    PYDANTIC_AI = 'pydantic_ai',
    PYTHON = 'python',
    REACT = 'react',
    REACT_NATIVE = 'react_native',
    REACT_ROUTER = 'react_router',
    REMIX = 'remix',
    RETOOL = 'retool',
    ROBLOX = 'roblox',
    RUBY = 'ruby',
    RUBY_ON_RAILS = 'ruby_on_rails',
    RUDDERSTACK = 'rudderstack',
    RUST = 'rust',
    SEGMENT = 'segment',
    SEMANTIC_KERNEL = 'semantic_kernel',
    SENTRY = 'sentry',
    SHOPIFY = 'shopify',
    SMOLAGENTS = 'smolagents',
    SVELTE = 'svelte',
    TRACELOOP = 'traceloop',
    TANSTACK_START = 'tanstack_start',
    TOGETHER_AI = 'together_ai',
    UNITY = 'unity',
    VERCEL_AI = 'vercel_ai',
    VERCEL_AI_GATEWAY = 'vercel_ai_gateway',
    VITE = 'vite',
    VUE_JS = 'vuejs',
    WEBFLOW = 'webflow',
    WORDPRESS = 'wordpress',
    XAI = 'xai',
    ZAPIER = 'zapier',
    HONO = 'hono',
}

export enum SDKTag {
    POPULAR = 'Most popular',
    WEB = 'Web',
    MOBILE = 'Mobile',
    SERVER = 'Server',
    LLM = 'LLM',
    FRAMEWORK = 'Framework',
    MODEL_PROVIDER = 'Model provider',
    GATEWAY = 'Gateway',
    INTEGRATION = 'Integration',
    OTHER = 'Other',
}

export type SDKInstructionsMap = Partial<Record<SDKKey, React.ComponentType>>
export type SDKDocsLinkOverrides = Partial<Record<SDKKey, string>>
export type SDKTagOverrides = Partial<Record<SDKKey, SDKTag[]>>

export enum SidePanelTab {
    Max = 'max',
    Notebooks = 'notebook',
    Support = 'support',
    Activity = 'activity',
    Discussion = 'discussion',
    Exports = 'exports',
    AccessControl = 'access-control',
    /** Access detail for one member or role. Opened programmatically from access control settings. */
    AccessDetail = 'access-detail',
    Info = 'info',
    // A canvas scene replaces the general tabs with its own panel tabs.
    CanvasChat = 'canvas-chat',
    CanvasBlocks = 'canvas-blocks',
    CanvasTimeline = 'canvas-timeline',
}

export interface ProductPricingTierSubrows {
    columns: LemonTableColumns<BillingTableTierAddonRow>
    rows: BillingTableTierAddonRow[]
}

export type BillingTableTierAddonRow = {
    productName: string
    price: string
    usage: string
    total: string
    projectedTotal: string
    icon?: string
}

export type BillingTableTierRow = {
    volume: string
    basePrice: string
    usage: string
    total: string
    projectedTotal: string | ReactNode
    subrows: ProductPricingTierSubrows
}

export type BillingInvoiceItemRow = {
    description: string
    dateRange?: string
    amount: string
    isBold?: boolean
}

export type AvailableOnboardingProducts = Record<
    | ProductKey.PRODUCT_ANALYTICS
    | ProductKey.SESSION_REPLAY
    | ProductKey.FEATURE_FLAGS
    | ProductKey.EXPERIMENTS
    | ProductKey.SURVEYS
    | ProductKey.DATA_WAREHOUSE
    | ProductKey.WEB_ANALYTICS
    | ProductKey.ERROR_TRACKING
    | ProductKey.AI_OBSERVABILITY
    | ProductKey.WORKFLOWS
    | ProductKey.LOGS
    | ProductKey.METRICS
    | ProductKey.MCP_ANALYTICS
    | ProductKey.CONVERSATIONS,
    OnboardingProduct
>

export type OnboardingProduct = {
    name: string
    breadcrumbsName?: string
    description: string
    icon: string
    iconColor: string
    url: string
    scene: Scene
    setupEffort?: 'automatic' | 'low' | 'medium'
    socialProof?: string
    userCentricDescription?: string
    capabilities?: string[]
    /** Title + problem pairs shown in the post-onboarding modal. Falls back to capabilities if absent. */
    valueProps?: { title: string; problem: string }[]
    /** Hedgehog illustration for the post-onboarding modal. Falls back to HedgehogSuperhero if absent. */
    hedgehog?: React.ComponentType<{ className?: string }>
}

export type CyclotronJobInputSchemaType = {
    type:
        | 'string'
        | 'number'
        | 'boolean'
        | 'dictionary'
        | 'choice'
        | 'json'
        | 'integration'
        | 'integration_multi'
        | 'integration_field'
        | 'email'
        | 'native_email'
        | 'posthog_assignee'
        | 'posthog_ticket_tags'
        | 'posthog_business_hours'
        | 'non_failure_status_codes'
        | 'customer_analytics_account_properties'
        | 'customer_analytics_account_relationships'
        | 'task_model'
        | 'task_repository'
        | 'task_mcp_installations'
        | 'signals_scout'
        | 'posthog_survey'
        | 'replay_vision_scan'
        | 'task_skills'
    key: string
    label: string
    choices?: { value: string; label: string }[]
    /** For `choice` inputs: render as a searchable select instead of a plain dropdown. */
    searchable?: boolean
    required?: boolean
    default?: any
    secret?: boolean
    hidden?: boolean
    templating?: boolean
    description?: string
    integration?: string
    integration_key?: string
    integration_field?: string
    requires_field?: string
    requiredScopes?: string
}

export type CyclotronJobMasking = {
    ttl: number | null
    threshold?: number | null
    hash: string
    bytecode?: any
}

// subset of ActionFilter
export interface CyclotronJobFilterBase {
    id: string
    name?: string | null
    order?: number
    properties?: (EventPropertyFilter | PersonPropertyFilter | ElementPropertyFilter)[]
}

export interface CyclotronJobFilterEvents extends CyclotronJobFilterBase {
    type: 'events'
}

export interface CyclotronJobFilterDataWarehouse extends CyclotronJobFilterBase {
    type: 'data_warehouse'
    uuid: string
    table_name: string
    id_field: string
    timestamp_field: string
    distinct_id_field: string
}

export interface CyclotronJobFilterActions extends CyclotronJobFilterBase {
    type: 'actions'
}

export type CyclotronJobFilterPropertyFilter =
    | EventPropertyFilter
    | EventMetadataPropertyFilter
    | PersonPropertyFilter
    | ElementPropertyFilter
    | GroupPropertyFilter
    | FeaturePropertyFilter
    | HogQLPropertyFilter
    | FlagPropertyFilter

export interface CyclotronJobFiltersType {
    source?: 'events' | 'internal-events' | 'person-updates' | 'data-warehouse-table' | 'data-warehouse-view'
    events?: CyclotronJobFilterEvents[]
    data_warehouse?: CyclotronJobFilterDataWarehouse[]
    actions?: CyclotronJobFilterActions[]
    properties?: CyclotronJobFilterPropertyFilter[]
    filter_test_accounts?: boolean
    bytecode?: any[]
    bytecode_error?: string
}

export type CyclotronJobInputType = CyclotronInputType

export interface HogFunctionMappingType {
    name: string
    inputs_schema?: CyclotronJobInputSchemaType[]
    inputs?: Record<string, CyclotronInputType> | null
    filters?: CyclotronJobFiltersType | null
    use_all_events_by_default?: boolean
}
export interface HogFunctionMappingTemplateType extends HogFunctionMappingType {
    name: string
    include_by_default?: boolean
}

export type HogFunctionTypeType =
    | 'destination'
    | 'internal_destination'
    | 'source'
    | 'source_webhook'
    | 'site_destination'
    | 'site_app'
    | 'transformation'
    | 'transformation_log'
    | 'legacy_destination'

export type HogFunctionType = {
    id: string
    type: HogFunctionTypeType
    icon_url?: string
    icon_class_name?: string // allow for overriding css styling on the icon case by case
    name: string
    description: string
    created_by: UserBasicType | null
    created_at: string
    updated_at: string
    enabled: boolean
    hog: string
    execution_order?: number
    inputs_schema?: CyclotronJobInputSchemaType[]
    inputs?: Record<string, CyclotronInputType> | null
    mappings?: HogFunctionMappingType[] | null
    masking?: CyclotronJobMasking | null
    filters?: CyclotronJobFiltersType | null
    template?: HogFunctionTemplateType
    status?: HogFunctionStatus
    batch_export_id?: string | null
    template_id?: string
    deleted?: boolean
    /** Config staged for review by an agent, not live until published. Null when nothing is staged. */
    draft?: HogFunctionDraftType | null
    draft_updated_at?: string | null
}

export type HogFunctionDraftType = Partial<
    Pick<HogFunctionType, 'hog' | 'inputs_schema' | 'inputs' | 'filters' | 'mappings' | 'masking'>
>

export type HogFunctionTemplateStatus = 'stable' | 'alpha' | 'beta' | 'deprecated' | 'coming_soon' | 'hidden'

// Contexts change the way the UI is rendered allowing different teams to customize the UI for their use case
export type HogFunctionConfigurationContextId =
    | 'standard'
    | 'error-tracking'
    | 'activity-log'
    | 'discussion-mention'
    | 'insight-alerts'
    | 'experiment-alerts'
    | 'logs-alerting'
    | 'health-alerts'
    | 'batch-export-alerts'
    | 'billing-alerts'
    | 'replay-vision-alerts'
    | 'replay-vision-requests'

export type HogFunctionSubTemplateIdType =
    | 'early-access-feature-enrollment'
    | 'survey-response'
    | 'mcp-tool-error'
    | 'pa-rageclick'
    | 'activity-log'
    | 'feature-flag-change'
    | 'error-tracking-issue-created'
    | 'error-tracking-issue-reopened'
    | 'error-tracking-issue-spiking'
    | 'discussion-mention'
    | 'insight-alert-firing'
    | 'experiment-significant'
    | 'logs-alert-firing'
    | 'logs-alert-resolved'
    | 'logs-alert-auto-disabled'
    | 'logs-alert-errored'
    | 'health-check-firing'
    | 'health-check-resolved'
    | 'batch-export-run-failed'
    | 'replay-vision-request-completed'

export type HogFunctionConfigurationType = Omit<
    HogFunctionType,
    'id' | 'created_at' | 'created_by' | 'updated_at' | 'status' | 'hog'
> & {
    hog?: HogFunctionType['hog'] // In the config it can be empty if using a template
    _create_in_folder?: string | null
}
export type HogFlowConfigurationType = Omit<HogFlow, 'id' | 'created_at' | 'created_by' | 'updated_at' | 'status'>
export type CyclotronJobConfigurationType = HogFunctionConfigurationType | HogFlowConfigurationType

export type HogFunctionSubTemplateType = Pick<
    HogFunctionType,
    'filters' | 'inputs' | 'masking' | 'mappings' | 'type'
> & {
    template_id: HogFunctionTemplateType['id']
    context_id: HogFunctionConfigurationContextId
    sub_template_id: HogFunctionSubTemplateIdType
    name?: string
    description?: string
    flag?: string
}

export type HogFunctionTemplateType = Pick<
    HogFunctionType,
    'id' | 'type' | 'name' | 'inputs_schema' | 'filters' | 'icon_url' | 'icon_class_name' | 'masking' | 'mappings'
> & {
    status: HogFunctionTemplateStatus
    free: boolean
    mapping_templates?: HogFunctionMappingTemplateType[]
    description?: string | JSX.Element
    code: string
    code_language: 'javascript' | 'hog'
    /** Whether the template should be conditionally rendered based on a feature flag */
    flag?: string
    /** Whether this is a featured/recommended source */
    featured?: boolean
    /** Release status, only populated for `type: 'source'` templates */
    releaseStatus?: 'beta' | 'ga'
}

export type HogFunctionTemplateWithSubTemplateType = HogFunctionTemplateType & {
    sub_template_id?: HogFunctionSubTemplateIdType
}

export type HogFunctionIconResponse = {
    id: string
    name: string
    url: string
}

export enum HogWatcherState {
    healthy = 1,
    overflowed = 2,
    disabled = 3,
    forcefully_degraded = 11,
    forcefully_disabled = 12,
}

export type HogFunctionStatus = {
    state: HogWatcherState
    tokens: number
}

export type CyclotronJobInvocationGlobals = {
    project: {
        id: number
        name: string
        url: string
    }
    source?: {
        id?: string
        name: string
        url: string
    }
    event: {
        uuid: string
        event: string
        elements_chain: string
        distinct_id: string
        properties: Record<string, any>
        timestamp: string
        url: string
    }
    person?: {
        id: string
        properties: Record<string, any>
        name: string
        url: string
    }
    groups?: Record<
        string,
        {
            id: string // the "key" of the group
            type: string
            index: number
            url: string
            properties: Record<string, any>
        }
    >
    // Only applies to sources
    request?: {
        body: Record<string, any>
        headers: Record<string, string>
        ip?: string
    }
    // Only applies to log transformations (see buildLogRecordGlobals)
    record?: {
        body: string | null
        attributes: Record<string, string>
        resource_attributes: Record<string, string>
        severity_text: string | null
        severity_number: number | null
        service_name: string | null
        instrumentation_scope: string | null
        event_name: string | null
        timestamp: number | null
        observed_timestamp: number | null
        trace_id: string | null
        span_id: string | null
    }
    // For HogFlows, workflow-level variables
    variables?: Record<string, any>
}

export type CyclotronJobInvocationGlobalsWithInputs = Partial<CyclotronJobInvocationGlobals> & {
    inputs?: Record<string, any>
}

export type CyclotronJobTestInvocationResult = {
    status: 'success' | 'error' | 'skipped'
    logs: LogEntry[]
    result: any
    errors?: string[]
}

export type AppMetricsV2Response = {
    labels: string[]
    series: {
        name: string
        values: number[]
    }[]
}

export type AppMetricsTotalsV2Response = {
    totals: Record<string, number>
}

export type AppMetricsV2RequestParams = {
    after?: string
    before?: string
    // Comma separated list of log levels
    name?: string
    kind?: string
    interval?: 'hour' | 'day' | 'week'
    breakdown_by?: 'name' | 'kind'
}

export type ReplayTemplateType = {
    key: string
    name: string
    description: string
    variables?: ReplayTemplateVariableType[]
    categories: ReplayTemplateCategory[]
    icon?: ReactNode
    order?: RecordingOrder
}
export type ReplayTemplateCategory = 'B2B' | 'B2C' | 'More'

export type ReplayTemplateVariableType = {
    type: 'event' | 'pageview' | 'person-property' | 'snapshot_source'
    name: string
    key: string
    touched?: boolean
    value?: string
    description?: string
    filterGroup?: UniversalFiltersGroupValue
    noTouch?: boolean
}

export type GoogleAdsConversionActionType = {
    id: string
    name: string
    resourceName: string
}

export type LinkedInAdsConversionRuleType = {
    id: number
    name: string
}

export type LinkedInAdsAccountType = {
    id: number
    name: string
    campaigns: string
}

export type DataColorThemeModel = {
    id: number
    name: string
    colors: string[]
    is_global: boolean
}

export type DataColorThemeModelPayload = Omit<DataColorThemeModel, 'id' | 'is_global'> & {
    id?: number
    is_global?: boolean
}

export enum CookielessServerHashMode {
    Disabled = 0,
    Stateless = 1,
    Stateful = 2,
}

/**
 * Assistant Conversation
 */
export enum ConversationStatus {
    Idle = 'idle',
    InProgress = 'in_progress',
    Canceling = 'canceling',
}

export enum ConversationType {
    Assistant = 'assistant',
    ToolCall = 'tool_call',
    DeepResearch = 'deep_research',
}

export enum Category {
    DEEP_RESEARCH = 'deep_research',
}

export enum DeepResearchType {
    PLANNING = 'planning',
    REPORT = 'report',
}

interface _NotebookBase {
    notebook_id: string
    title: string
}

export interface DeepResearchNotebook extends _NotebookBase {
    category: Category.DEEP_RESEARCH
    notebook_type?: DeepResearchType
}

export type NotebookInfo = DeepResearchNotebook

export type ApprovalDecisionStatus = 'pending' | 'approved' | 'rejected' | 'auto_rejected'

export interface PendingApproval {
    proposal_id: string
    decision_status: ApprovalDecisionStatus
    tool_name: string
    preview: string
    payload: Record<string, unknown>
    original_tool_call_id?: string
    message_id?: string
}

export interface ConversationQueueMessage {
    id: string
    content: string
    created_at: string
    contextual_tools?: Record<string, any> | null
    ui_context?: Record<string, any> | null
    billing_context?: Record<string, any> | null
    agent_mode?: string | null
    session_id?: string | null
}

export interface ConversationQueueResponse {
    messages: ConversationQueueMessage[]
    max_queue_messages: number
}

export type ConversationTopic =
    | 'web_analytics'
    | 'product_analytics'
    | 'session_replay'
    | 'surveys'
    | 'feature_flags'
    | 'experiments'
    | 'error_tracking'
    | 'data_warehouse'
    | 'other'

export interface Conversation {
    id: string
    user: UserBasicType
    status: ConversationStatus
    title: string | null
    /** Product domain classified from the first question; drives contextual nudges. */
    topic?: ConversationTopic | null
    created_at: string | null
    updated_at: string | null
    type: ConversationType
    has_unsupported_content?: boolean
    agent_mode?: string | null
    slack_thread_key?: string | null
    slack_workspace_domain?: string | null
    is_internal?: boolean
    pending_approvals?: PendingApproval[]
    is_sandbox?: boolean
    /**
     * Runtime the conversation was created on. Stamped at create-time from the `phai-sandbox-mode`
     * flag and never re-read. Existing rows default to `'langgraph'`.
     */
    agent_runtime?: 'langgraph' | 'sandbox'
    /** Backing products/tasks Task for sandbox conversations. Null until the first message creates it. `latest_run` is the newest TaskRun id used to bootstrap the sandbox stream. */
    task?: { id: string; latest_run: string | null; runtime?: TaskRuntimeEnumApi } | null
}

export interface ConversationDetail extends Conversation {
    /** undefined = not yet fetched, [] = fetched but empty, [...] = fetched with content */
    messages?: RootAssistantMessage[]
}

export enum UserRole {
    Engineering = 'engineering',
    Data = 'data',
    Product = 'product',
    Founder = 'founder',
    Leadership = 'leadership',
    Marketing = 'marketing',
    Sales = 'sales',
    Student = 'student',
    Other = 'other',
}

export interface CoreMemory {
    id: string
    text: string
}

export type FileSystemIconColor = [string] | [string, string]

export interface FileSystemType {
    href?: (ref: string) => string
    // The product's own list page, which Library opens for this type instead of its generic table
    listHref?: () => string
    // The URL param the list page reads its search text from, so Command K's "View all" row can carry the search over
    listSearchParam?: 'search'
    // Visual name of the product
    name: string
    // Flag to determine if the product is enabled
    flag?: string
    // Used to filter the tree items by product
    filterKey?: string
    // Icon type of the icon
    iconType?: FileSystemIconType
    // Color of the icon
    iconColor?: FileSystemIconColor
}

export interface FeaturePreviewGateConfig {
    flag: string
    title: string
    description: string
    docsURL?: string
    /**
     * Scene whose name and icon the gated state renders as its header. Without it the gate
     * falls back to the router's active scene, which can resolve to Error404 ("Not found")
     * and mislabel the page.
     */
    sceneId?: string
    /**
     * Offer a "Request access" support CTA. Set this for betas that aren't self-serve early-access
     * features, so the gated state offers a way to request access instead of dead-ending on the
     * feature previews page.
     */
    offerRequestAccess?: boolean
    /**
     * Product intent recorded when a user joins the waitlist from the gate, so waitlist sign-ups
     * count as product intent the same way opting in from the feature previews page does. When
     * set, the gate also reads this product's setup-detection status to end the post-enrollment
     * "turning it on" state as soon as the API agrees the flag is on, instead of waiting out a
     * fixed timer.
     */
    productIntent?: ProductKey
}

export interface ProductManifest {
    name: string
    scenes?: Record<string, SceneConfig>
    routes?: Record<string, [string /** Scene */, string /** Scene Key (unique for layout tabs) */]>
    redirects?: Record<string, string | ((params: Params, searchParams: Params, hashParams: Params) => string)>
    urls?: Record<string, string | ((...args: any[]) => string)>
    fileSystemTypes?: Record<string, FileSystemType>
    treeItemsNew?: FileSystemImport[]
    treeItemsProducts?: (FileSystemImport & { intents: ProductKey[]; category: ProductItemCategory })[] // Require `intents` and `category to be set for products
    treeItemsGames?: FileSystemImport[]
    treeItemsMetadata?: FileSystemImport[]
    /**
     * Setup-status probe for this product's empty state. Aggregated across
     * manifests into `productSetupProbes` and answered by one property-definition
     * request after login (see `productSetupPreloadLogic`).
     */
    setupProbe?: ProductSetupProbe
    /** Aggregated into `productActivityDescribers`, which loads each one on demand. */
    activityDescribers?: Partial<Record<ActivityScope, () => Promise<Describer>>>
    /** Aggregated into `productGlobalModals`. Each one renders on every logged-in page and owns its open state. */
    globalModals?: Record<string, () => Promise<ComponentType>>
}

export interface ProjectTreeRef {
    /**
     * Type of file system object.
     * Use "/" as a separator to add an internal type, e.g. "hog/site_destination".
     * Search with "hog/" to match all internal types.
     */
    type: string
    /**
     * The ref of the file system object.
     * Usually the "id" or "short_id" of the database object.
     * "null" opens the "new" page
     */
    ref: string | null
}

export type OAuthMcpConsentContext = {
    is_mcp_resource: boolean
    scopes?: string[]
}

export type OAuthScopeResolution = {
    /** What `/authorize` resolved the request to: clamped to the app ceiling, and defaulted to it when the client sent no usable scope. */
    scopes: string[]
    /** Whether the client sent no usable `scope` (omitted, or cut off mid-token), so the server picked the set. */
    was_defaulted: boolean
    /** Scopes of `scopes` the user granted this app before, which a step-up keeps. Shown as granted and not removable. */
    already_granted_scopes?: string[]
    /** Where the newest earlier grant applies. A step-up pre-selects it, so the token keeps its projects. Both lists empty means all of them. */
    earlier_access?: { scoped_teams: number[]; scoped_organizations: string[] }
}

export type OAuthApplicationPublicMetadata = {
    name: string
    client_id: string
    is_verified: boolean
    logo_uri: string | null
    /** Scopes the user cannot deselect at consent. Empty unless the app declares optional scopes. */
    required_scopes?: string[]
    /** Server-computed read-only form of a `*` grant; the consent page must not derive this client-side. */
    wildcard_read_scopes?: string[]
    /**
     * The app's resolved scope ceiling. `/authorize` clamps the request to this set, so a requested
     * scope missing from it is dropped rather than granted and must not be rendered as a consent row.
     */
    grantable_scopes?: string[]
}
export interface EmailSenderDomainStatus {
    status: 'pending' | 'success'
    dnsRecords: (
        | {
              type: 'dkim'
              recordType: 'TXT'
              recordHostname: string
              recordValue: string
              status: 'pending' | 'success'
          }
        | {
              type: 'spf'
              recordType: 'TXT'
              recordHostname: '@'
              recordValue: string
              status: 'pending' | 'success'
          }
        | {
              type: 'mail_from'
              recordType: 'TXT' | 'MX'
              recordHostname: string
              recordValue: string
              status: 'pending' | 'success'
              priority?: number
          }
    )[]
}

export interface DataWarehouseSourceRowCount {
    breakdown_of_rows_by_source: Record<string, number>
    billing_available: boolean
    billing_interval: string
    billing_period_end: string
    billing_period_start: string
    materialized_rows_in_billing_period: number
    total_rows: number
    tracked_billing_rows: number
    pending_billing_rows: number
}

export interface DataWarehouseActivityRecord {
    id: string
    type: string
    name: string | null
    status: ExternalDataJobStatus
    rows: number
    created_at: string
    finished_at: string | null
    latest_error: string | null
    workflow_run_id?: string
    origin?: DataWarehouseSavedQueryOrigin | null
}

export type HeatmapType = 'screenshot' | 'iframe' | 'recording'
export type HeatmapStatus = 'processing' | 'completed' | 'failed'
export type HeatmapSource = 'server' | 'toolbar'

export interface HeatmapScreenshotType {
    id: number
    name: string
    short_id: string
    url: string
    data_url: string | null
    type: HeatmapType
    width: number
    status: HeatmapStatus
    has_content: boolean
    block_consent_modals?: boolean
    created_at: string
    updated_at: string
    exception?: string
    error?: string // Added for error responses from content endpoint
    created_by?: UserBasicType | null
    user_access_level?: AccessControlLevel
}

export type HeatmapScreenshotContentResponse =
    | { success: true; data: Response } // 200: PNG image data
    | { success: false; data: HeatmapScreenshotType } // 202/404/501: JSON with screenshot metadata

export interface HeatmapSavedFilters {
    order: string
    search: string
    createdBy: number | 'All users'
    page: number
    limit: number
    offset: number
}

export interface DataWarehouseDashboardDataSource {
    id: string
    name: string
    status: string | null
    lastSync: string | null
    rowCount: number | null
    url: string
}

export interface DataWarehouseJobStatsRequestPayload {
    days: 1 | 7 | 30
}

export interface DataWarehouseJobStats {
    days: number
    cutoff_time: string
    total_jobs: number
    successful_jobs: number
    failed_jobs: number
    external_data_jobs: {
        total: number
        running: number
        successful: number
        failed: number
    }
    modeling_jobs: {
        total: number
        running: number
        successful: number
        failed: number
    }
    breakdown: Record<
        string,
        {
            successful: number
            failed: number
        }
    >
}

export enum OnboardingStepKey {
    INSTALL = 'install',
    LINK_DATA = 'link_data',
    PLANS = 'plans',
    VERIFY = 'verify',
    PRODUCT_CONFIGURATION = 'configure',
    REVERSE_PROXY = 'proxy',
    INVITE_TEAMMATES = 'invite_teammates',
    SESSION_REPLAY = 'session_replay',
    AUTHORIZED_DOMAINS = 'authorized_domains',
    SOURCE_MAPS = 'source_maps',
    ALERTS = 'alerts',
    PATH_CLEANING = 'path_cleaning',
}

// Managed viewset
export interface DataWarehouseManagedViewsetSavedQuery {
    id: string
    created_at: string
    created_by_id: string | null
    name: string
}

export interface QuickFilterOption {
    id: string
    value: string | string[] | null
    label: string
    operator: PropertyOperator
}

export interface QuickFilter {
    id: string
    name: string
    property_name: string
    type: QuickFilterType
    options: QuickFilterOption[]
    contexts: QuickFilterContext[]
    created_at: string
    updated_at: string
}

// Approval Workflows
export enum ChangeRequestState {
    Pending = 'pending',
    Approved = 'approved',
    Applied = 'applied',
    Rejected = 'rejected',
    Expired = 'expired',
    Failed = 'failed',
}

export enum ApprovalDecision {
    Approved = 'approved',
    Rejected = 'rejected',
}

export enum ValidationStatus {
    Valid = 'valid',
    Invalid = 'invalid',
    Expired = 'expired',
    Stale = 'stale',
}

export interface Approval {
    id: string
    created_by: UserBasicType
    decision: ApprovalDecision
    reason: string
    created_at: string
}

export interface DecisionAnalysis {
    status: ChangeRequestState
    summary: string
    details: string
    votes: {
        approved: number
        rejected: number
        total: number
        quorum: number
    }
}

export interface ChangeRequest {
    id: string
    action_key: string
    action_version: number
    resource_type: string
    resource_id: string | null
    intent: Record<string, any>
    intent_display: Record<string, any>
    policy_snapshot: Record<string, any>
    validation_status: ValidationStatus
    validation_errors: Record<string, any> | null
    validated_at: string | null
    state: ChangeRequestState
    created_by: UserBasicType
    applied_by: UserBasicType | null
    created_at: string
    updated_at: string
    expires_at: string
    applied_at: string | null
    apply_error: string
    result_data: Record<string, any> | null
    approvals: Approval[]
    can_approve: boolean
    can_cancel: boolean
    is_requester: boolean
    user_decision: string | null
}

export enum CustomerProfileScope {
    PERSON = 'person',
    GROUP_0 = 'group_0',
    GROUP_1 = 'group_1',
    GROUP_2 = 'group_2',
    GROUP_3 = 'group_3',
    GROUP_4 = 'group_4',
}

export interface CustomerProfileConfigType {
    id: string
    team: number
    content: Record<string, any>
    sidebar: Record<string, any>
    scope: CustomerProfileScope
    created_at: string
    updated_at: string
}

export interface ApprovalPolicy {
    id: string
    action_key: string
    conditions: Record<string, any>
    approver_config: Record<string, any>
    allow_self_approve: boolean
    bypass_org_membership_levels: string[]
    bypass_roles: string[]
    expires_after: string
    enabled: boolean
    created_by: UserBasicType
    created_at: string
    updated_at: string
}

export interface WebAnalyticsFiltersConfig {
    properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter)[]
    dateFrom?: string | null
    dateTo?: string | null
    interval?: IntervalType
    compareFilter?: { compare?: boolean; compare_to?: string | null }
    domainFilter?: string | null
    deviceTypeFilter?: string | null
    countryFilter?: string | null
    referrerFilter?: string | null
    conversionGoal?: { actionId?: number; customEventName?: string } | null
    isPathCleaningEnabled?: boolean
    shouldFilterTestAccounts?: boolean
}

export interface WebAnalyticsFilterPresetType {
    id: number
    short_id: string
    name: string
    description: string
    pinned: boolean
    deleted: boolean
    filters: WebAnalyticsFiltersConfig
    created_at: string
    created_by: UserBasicType | null
    last_modified_at: string
    last_modified_by: UserBasicType | null
}