/**
 * Tool Method Maps
 *
 * Single source of truth for tool -> method -> params -> result type mappings.
 * Used by SDK adapters (compile-time typed wrappers) and optionally by the
 * server-side dispatcher for type checking.
 *
 * Browser-safe: no Node.js imports, pure type definitions.
 */

import type {
  CreateRecordParams,
  CreateRecordResult,
  UpdateRecordParams,
  UpdateRecordResult,
  QueryRecordsParams,
  QueryRecordsResult,
  GetRecordParams,
  GetRecordResult,
  DeleteRecordParams,
  DeleteRecordResult,
  ListObjectsResult,
  ListAttributesParams,
  ListAttributesResult,
  CreateAttributeParams,
  CreateAttributeResult,
  UpdateAttributeParams,
  UpdateAttributeResult,
  CreateNoteParams,
  CreateNoteResult,
  ListNotesParams,
  ListNotesResult,
  DeleteNoteParams,
  DeleteNoteResult
} from './integration/types/attio'

import type {
  RunActorParams,
  RunActorResult,
  GetDatasetItemsParams,
  GetDatasetItemsResult,
  StartActorParams,
  StartActorResult
} from './integration/types/apify'

import type {
  UploadFileParams,
  UploadFileResult,
  CreateFolderParams,
  CreateFolderResult
} from './integration/types/dropbox'

import type { GmailSendEmailParams, GmailSendEmailResult } from './integration/types/gmail'

import type {
  ReadSheetParams,
  ReadSheetResult,
  WriteSheetParams,
  WriteSheetResult,
  AppendRowsParams,
  AppendRowsResult,
  ClearRangeParams,
  ClearRangeResult,
  GetSpreadsheetMetadataParams,
  GetSpreadsheetMetadataResult,
  BatchUpdateParams,
  BatchUpdateResult,
  GetHeadersParams,
  GetHeadersResult,
  GetLastRowParams,
  GetLastRowResult,
  GetRowByValueParams,
  GetRowByValueResult,
  UpdateRowByValueParams,
  UpdateRowByValueResult,
  UpsertRowParams,
  UpsertRowResult,
  FilterRowsParams,
  FilterRowsResult,
  DeleteRowByValueParams,
  DeleteRowByValueResult
} from './integration/types/google-sheets'

import type {
  SendReplyParams,
  SendReplyResult,
  RemoveFromSubsequenceParams,
  RemoveFromSubsequenceResult,
  GetEmailsParams,
  GetEmailsResult,
  UpdateInterestStatusParams,
  UpdateInterestStatusResult,
  AddToCampaignParams,
  AddToCampaignResult,
  ListCampaignsParams,
  ListCampaignsResult,
  GetCampaignParams,
  GetCampaignResult,
  UpdateCampaignParams,
  UpdateCampaignResult,
  PauseCampaignParams,
  PauseCampaignResult,
  ActivateCampaignParams,
  ActivateCampaignResult,
  GetCampaignAnalyticsParams,
  GetCampaignAnalyticsResult,
  GetStepAnalyticsParams,
  GetStepAnalyticsResult,
  BulkAddLeadsParams,
  BulkAddLeadsResult,
  GetAccountHealthParams,
  GetAccountHealthResult,
  CreateInboxTestParams,
  CreateInboxTestResult,
  CreateCampaignParams,
  CreateCampaignResult,
  GetDailyCampaignAnalyticsParams,
  GetDailyCampaignAnalyticsResult,
  ListLeadsParams,
  ListLeadsResult,
  BulkDeleteLeadsParams,
  BulkDeleteLeadsResult,
  DeleteCampaignParams,
  DeleteCampaignResult,
  PatchLeadParams,
  PatchLeadResult
} from './integration/types/instantly'

import type {
  MillionVerifierVerifyEmailParams,
  MillionVerifierVerifyEmailResult,
  MillionVerifierCheckCreditsParams,
  MillionVerifierCheckCreditsResult
} from './integration/types/millionverifier'

import type {
  ClickUpVerifyParams,
  ClickUpVerifyResult,
  ClickUpCreateTaskParams,
  ClickUpCreateTaskResult
} from './integration/types/clickup'

import type {
  FindCompanyEmailParams,
  FindCompanyEmailResult,
  FindPersonEmailParams,
  FindPersonEmailResult,
  FindDecisionMakerEmailParams,
  FindDecisionMakerEmailResult,
  VerifyEmailParams,
  VerifyEmailResult
} from './integration/types/anymailfinder'

import type {
  EmailFinderParams,
  EmailFinderResult,
  DomainSearchParams,
  DomainSearchResult,
  EmailVerifierParams,
  EmailVerifierResult
} from './integration/types/tomba'

import type {
  ResendSendEmailParams,
  ResendSendEmailResult,
  ResendGetEmailParams,
  ResendGetEmailResult
} from './integration/types/resend'

import type {
  CreateEnvelopeParams,
  CreateEnvelopeResult,
  VoidEnvelopeParams,
  VoidEnvelopeResult,
  DownloadDocumentParams,
  DownloadDocumentResult,
  GetEnvelopeParams,
  GetEnvelopeResult
} from './integration/types/signature-api'

import type {
  CreatePaymentLinkParams,
  CreatePaymentLinkResult,
  GetPaymentLinkParams,
  GetPaymentLinkResult,
  UpdatePaymentLinkParams,
  UpdatePaymentLinkResult,
  ListPaymentLinksParams,
  ListPaymentLinksResult,
  CreateAutoPaymentLinkParams,
  CreateAutoPaymentLinkResult,
  CreateCheckoutSessionParams,
  CreateCheckoutSessionResult
} from './integration/types/stripe'

import type {
  StorageUploadInput,
  StorageUploadOutput,
  StorageDownloadInput,
  StorageDownloadOutput,
  StorageSignedUrlInput,
  StorageSignedUrlOutput,
  StorageDeleteInput,
  StorageDeleteOutput,
  StorageListInput,
  StorageListOutput
} from './platform/storage/types'

import type { CreateScheduleInput, TaskSchedule } from '../../scheduler/types'

import type { CreateNotificationParams } from '../../../operations/notifications/types'

import type {
  AcqList,
  AcqCompany,
  AcqContact,
  PaginatedResult,
  CreateListParams,
  UpdateListParams,
  CreateCompanyParams,
  UpdateCompanyParams,
  UpsertCompanyParams,
  CompanyFilters,
  CreateContactParams,
  UpdateContactParams,
  UpsertContactParams,
  ContactFilters,
  UpsertDealParams,
  AcqDeal,
  AcqDealNote,
  AcqDealTask,
  CreateDealNoteParams,
  ListDealNotesParams,
  CreateDealTaskParams,
  ListDealTasksParams,
  ListDealTasksDueParams,
  CompleteDealTaskParams,
  RecordDealActivityParams,
  AddContactsToListParams,
  AddContactsToListResult,
  AddCompaniesToListParams,
  AddCompaniesToListResult,
  BulkImportParams,
  BulkImportResult,
  BulkImportCompaniesParams,
  BulkImportCompaniesResult,
  UpdateDiscoveryDataParams,
  UpdateProposalDataParams,
  MarkProposalSentParams,
  MarkProposalReviewedParams,
  UpdateCloseLostReasonParams,
  UpdateFeesParams,
  CacheInstantlyThreadIdsParams,
  TransitionItemParams,
  SetContactNurtureParams,
  CancelSchedulesAndHitlByEmailParams,
  CancelHitlByDealIdParams,
  ClearDealFieldsParams,
  DeleteDealParams,
  DealFilters,
  DealPipelineAnalytics,
  ScrapingConfig,
  IcpRubric,
  PipelineConfig,
  RecordListExecutionParams,
  UpdateCompanyStageParams,
  UpdateContactStageParams,
  ClearCompanyStagesParams,
  ClearContactStagesParams,
  ListPendingCompanyIdsParams,
  ListPendingContactIdsParams,
  UpsertSocialPostParams,
  UpsertSocialPostsResult,
  GetDealByIdParams,
  GetContactByIdParams,
  GetCompanyByIdParams
} from './lead-service-types'

import type { DealListItem, DealDetail } from '../../../business/acquisition'
import { CrmSchemas } from '../../../business/sales/api-schemas'
import type { RecentActivityEntry } from '../../../business/sales/api-schemas'
import { DealSchemas } from '../../../business/acquisition'
import { ProjectSchemas } from '../../../projects/api-schemas'
import type {
  ProjectRow,
  MilestoneRow,
  TaskRow,
  NoteRow,
  ProjectWithCounts,
  ProjectDetail
} from '../../../business/projects'
import type { z } from 'zod'

// ---------------------------------------------------------------------------
// Generic constraint types
// ---------------------------------------------------------------------------

/** A single method entry: what params go in, what result comes out */
export interface MethodEntry {
  params: unknown
  result: unknown
}

/** A tool's complete method map: method name -> MethodEntry */
export type ToolMethodMap = Record<string, MethodEntry>

// ---------------------------------------------------------------------------
// Attio (integration adapter, 12 methods)
// ---------------------------------------------------------------------------

export type AttioToolMap = {
  createRecord: { params: CreateRecordParams; result: CreateRecordResult }
  updateRecord: { params: UpdateRecordParams; result: UpdateRecordResult }
  listRecords: { params: QueryRecordsParams; result: QueryRecordsResult }
  getRecord: { params: GetRecordParams; result: GetRecordResult }
  deleteRecord: { params: DeleteRecordParams; result: DeleteRecordResult }
  listObjects: { params: Record<string, never>; result: ListObjectsResult }
  listAttributes: { params: ListAttributesParams; result: ListAttributesResult }
  createAttribute: { params: CreateAttributeParams; result: CreateAttributeResult }
  updateAttribute: { params: UpdateAttributeParams; result: UpdateAttributeResult }
  createNote: { params: CreateNoteParams; result: CreateNoteResult }
  listNotes: { params: ListNotesParams; result: ListNotesResult }
  deleteNote: { params: DeleteNoteParams; result: DeleteNoteResult }
}

// ---------------------------------------------------------------------------
// Scheduler (platform tool, 9 methods)
// ---------------------------------------------------------------------------

export type SchedulerToolMap = {
  createSchedule: { params: CreateScheduleInput; result: TaskSchedule }
  updateAnchor: { params: { scheduleId: string; anchorAt: string }; result: TaskSchedule }
  deleteSchedule: { params: { scheduleId: string }; result: void }
  findByIdempotencyKey: { params: { idempotencyKey: string }; result: TaskSchedule | null }
  deleteScheduleByIdempotencyKey: { params: { idempotencyKey: string }; result: void }
  listSchedules: { params: { status?: string; limit?: number; offset?: number }; result: TaskSchedule[] }
  getSchedule: { params: { scheduleId: string }; result: TaskSchedule }
  cancelSchedule: { params: { scheduleId: string }; result: void }
  cancelSchedulesByMetadata: { params: { metadata: Record<string, unknown> }; result: { cancelledCount: number } }
  cancelScheduleByIdempotencyKey: { params: { idempotencyKey: string }; result: { cancelled: boolean } }
}

// ---------------------------------------------------------------------------
// Storage (platform tool, 5 methods)
// ---------------------------------------------------------------------------

export type StorageToolMap = {
  upload: { params: StorageUploadInput; result: StorageUploadOutput }
  download: { params: StorageDownloadInput; result: StorageDownloadOutput }
  createSignedUrl: { params: StorageSignedUrlInput; result: StorageSignedUrlOutput }
  delete: { params: StorageDeleteInput; result: StorageDeleteOutput }
  list: { params: StorageListInput; result: StorageListOutput }
}

// ---------------------------------------------------------------------------
// Notification (platform tool, 1 method)
// ---------------------------------------------------------------------------

/**
 * SDK-side notification input.
 * Omits userId and organizationId which are injected server-side from execution context.
 */
export type NotificationSDKInput = Omit<CreateNotificationParams, 'userId' | 'organizationId'>

export type NotificationToolMap = {
  create: { params: NotificationSDKInput; result: void }
}

// ---------------------------------------------------------------------------
// Projects (platform tool, 18 methods)
// ---------------------------------------------------------------------------

type ProjectsListParams = z.infer<typeof ProjectSchemas.GetProjectsQuery>
type ProjectCreateParams = z.infer<typeof ProjectSchemas.CreateProjectRequest>
type ProjectUpdateParams = z.infer<typeof ProjectSchemas.UpdateProjectRequest>
type MilestoneCreateParams = z.infer<typeof ProjectSchemas.ProjectIdPathParams> &
  z.infer<typeof ProjectSchemas.CreateMilestoneRequest>
type MilestoneUpdateParams = z.infer<typeof ProjectSchemas.UpdateMilestoneRequest>
type TaskListParams = z.infer<typeof ProjectSchemas.ProjectIdPathParams> & z.infer<typeof ProjectSchemas.GetTasksQuery>
type TaskCreateParams = z.infer<typeof ProjectSchemas.CreateTaskRequest>
type TaskUpdateParams = z.infer<typeof ProjectSchemas.UpdateTaskRequest>
type TaskResumeContextParams = z.infer<typeof ProjectSchemas.TaskIdParams> &
  z.infer<typeof ProjectSchemas.MergeResumeContextRequest>
type NoteListParams = z.infer<typeof ProjectSchemas.ProjectIdPathParams>
type NoteCreateParams = z.infer<typeof ProjectSchemas.CreateNoteRequest>
type NoteUpdateParams = z.infer<typeof ProjectSchemas.UpdateNoteRequest>
type TaskResumeContextResult = Pick<TaskRow, 'id' | 'resume_context' | 'updated_at'>

export type ProjectsToolMap = {
  listProjects: { params: ProjectsListParams; result: ProjectWithCounts[] }
  getProject: { params: z.infer<typeof ProjectSchemas.ProjectIdParams>; result: ProjectDetail }
  createProject: { params: ProjectCreateParams; result: ProjectRow }
  updateProject: { params: z.infer<typeof ProjectSchemas.ProjectIdParams> & ProjectUpdateParams; result: ProjectRow }
  deleteProject: { params: z.infer<typeof ProjectSchemas.ProjectIdParams>; result: void }
  listMilestones: { params: z.infer<typeof ProjectSchemas.ProjectIdPathParams>; result: MilestoneRow[] }
  createMilestone: { params: MilestoneCreateParams; result: MilestoneRow }
  updateMilestone: {
    params: z.infer<typeof ProjectSchemas.MilestoneIdParams> & MilestoneUpdateParams
    result: MilestoneRow
  }
  deleteMilestone: { params: z.infer<typeof ProjectSchemas.MilestoneIdParams>; result: void }
  listTasks: { params: TaskListParams; result: TaskRow[] }
  getTask: { params: z.infer<typeof ProjectSchemas.TaskIdParams>; result: TaskRow }
  createTask: { params: TaskCreateParams; result: TaskRow }
  updateTask: { params: z.infer<typeof ProjectSchemas.TaskIdParams> & TaskUpdateParams; result: TaskRow }
  deleteTask: { params: z.infer<typeof ProjectSchemas.TaskIdParams>; result: void }
  mergeTaskResumeContext: { params: TaskResumeContextParams; result: TaskResumeContextResult }
  listNotes: { params: NoteListParams; result: NoteRow[] }
  createNote: { params: NoteCreateParams; result: NoteRow }
  updateNote: { params: z.infer<typeof ProjectSchemas.NoteIdParams> & NoteUpdateParams; result: NoteRow }
  deleteNote: { params: z.infer<typeof ProjectSchemas.NoteIdParams>; result: void }
}

// ---------------------------------------------------------------------------
// CRM (platform tool, 13 methods)
// ---------------------------------------------------------------------------

type CrmRecentActivityParams = Partial<z.infer<typeof CrmSchemas.GetRecentActivityQuery>>
type CrmListDealsParams = Partial<z.infer<typeof DealSchemas.ListDealsQuery>>
type CrmGetDealParams = z.infer<typeof DealSchemas.DealIdParams>
type CrmGetDealByEmailParams = { email: string }
type CrmTaskDueParams = Partial<z.infer<typeof DealSchemas.ListDealTasksDueQuery>>
type CrmDealTaskParams = Omit<CreateDealTaskParams, 'organizationId'>
type CrmDealNoteParams = Omit<CreateDealNoteParams, 'organizationId'>
type CrmRecordActivityParams = Omit<RecordDealActivityParams, 'organizationId'>
type CrmDeleteDealParams = Omit<DeleteDealParams, 'organizationId'>

export type CrmToolMap = {
  getRecentActivity: { params: CrmRecentActivityParams; result: RecentActivityEntry[] }
  listDeals: { params: CrmListDealsParams; result: DealListItem[] }
  getDeal: { params: CrmGetDealParams; result: DealDetail | null }
  getDealByEmail: { params: CrmGetDealByEmailParams; result: DealDetail | null }
  createDealNote: { params: CrmDealNoteParams; result: AcqDealNote }
  listDealNotes: { params: Omit<ListDealNotesParams, 'organizationId'>; result: AcqDealNote[] }
  createDealTask: { params: CrmDealTaskParams; result: AcqDealTask }
  listDealTasks: { params: Omit<ListDealTasksParams, 'organizationId'>; result: AcqDealTask[] }
  listDealTasksDue: { params: CrmTaskDueParams; result: AcqDealTask[] }
  completeDealTask: { params: Omit<CompleteDealTaskParams, 'organizationId'>; result: AcqDealTask }
  recordActivity: { params: CrmRecordActivityParams; result: void }
  deleteDeal: { params: CrmDeleteDealParams; result: void }
}

// ---------------------------------------------------------------------------
// Stripe (integration adapter, 6 methods)
// ---------------------------------------------------------------------------

export type StripeToolMap = {
  createPaymentLink: { params: CreatePaymentLinkParams; result: CreatePaymentLinkResult }
  getPaymentLink: { params: GetPaymentLinkParams; result: GetPaymentLinkResult }
  updatePaymentLink: { params: UpdatePaymentLinkParams; result: UpdatePaymentLinkResult }
  listPaymentLinks: { params: ListPaymentLinksParams; result: ListPaymentLinksResult }
  createAutoPaymentLink: { params: CreateAutoPaymentLinkParams; result: CreateAutoPaymentLinkResult }
  createCheckoutSession: { params: CreateCheckoutSessionParams; result: CreateCheckoutSessionResult }
}

// ---------------------------------------------------------------------------
// Google Sheets (integration adapter, 13 methods)
// ---------------------------------------------------------------------------

export type GoogleSheetsToolMap = {
  readSheet: { params: ReadSheetParams; result: ReadSheetResult }
  writeSheet: { params: WriteSheetParams; result: WriteSheetResult }
  appendRows: { params: AppendRowsParams; result: AppendRowsResult }
  clearRange: { params: ClearRangeParams; result: ClearRangeResult }
  getSpreadsheetMetadata: { params: GetSpreadsheetMetadataParams; result: GetSpreadsheetMetadataResult }
  batchUpdate: { params: BatchUpdateParams; result: BatchUpdateResult }
  getHeaders: { params: GetHeadersParams; result: GetHeadersResult }
  getLastRow: { params: GetLastRowParams; result: GetLastRowResult }
  getRowByValue: { params: GetRowByValueParams; result: GetRowByValueResult }
  updateRowByValue: { params: UpdateRowByValueParams; result: UpdateRowByValueResult }
  upsertRow: { params: UpsertRowParams; result: UpsertRowResult }
  filterRows: { params: FilterRowsParams; result: FilterRowsResult }
  deleteRowByValue: { params: DeleteRowByValueParams; result: DeleteRowByValueResult }
}

// ---------------------------------------------------------------------------
// Resend (integration adapter, 2 methods)
// ---------------------------------------------------------------------------

export type ResendToolMap = {
  sendEmail: { params: ResendSendEmailParams; result: ResendSendEmailResult }
  getEmail: { params: ResendGetEmailParams; result: ResendGetEmailResult }
}

// ---------------------------------------------------------------------------
// Apify (integration adapter, 2 methods)
// ---------------------------------------------------------------------------

export type ApifyToolMap = {
  runActor: { params: RunActorParams; result: RunActorResult }
  getDatasetItems: { params: GetDatasetItemsParams; result: GetDatasetItemsResult }
  startActor: { params: StartActorParams; result: StartActorResult }
}

// ---------------------------------------------------------------------------
// Gmail (integration adapter, 1 method)
// ---------------------------------------------------------------------------

export type GmailToolMap = {
  sendEmail: { params: GmailSendEmailParams; result: GmailSendEmailResult }
}

// ---------------------------------------------------------------------------
// Dropbox (integration adapter, 2 methods)
// ---------------------------------------------------------------------------

export type DropboxToolMap = {
  uploadFile: { params: UploadFileParams; result: UploadFileResult }
  createFolder: { params: CreateFolderParams; result: CreateFolderResult }
}

// ---------------------------------------------------------------------------
// SignatureAPI (integration adapter, 4 methods)
// ---------------------------------------------------------------------------

export type SignatureApiToolMap = {
  createEnvelope: { params: CreateEnvelopeParams; result: CreateEnvelopeResult }
  voidEnvelope: { params: VoidEnvelopeParams; result: VoidEnvelopeResult }
  downloadDocument: { params: DownloadDocumentParams; result: DownloadDocumentResult }
  getEnvelope: { params: GetEnvelopeParams; result: GetEnvelopeResult }
}

// ---------------------------------------------------------------------------
// Instantly (integration adapter, 21 methods)
// ---------------------------------------------------------------------------

export type InstantlyToolMap = {
  sendReply: { params: SendReplyParams; result: SendReplyResult }
  removeFromSubsequence: { params: RemoveFromSubsequenceParams; result: RemoveFromSubsequenceResult }
  getEmails: { params: GetEmailsParams; result: GetEmailsResult }
  updateInterestStatus: { params: UpdateInterestStatusParams; result: UpdateInterestStatusResult }
  addToCampaign: { params: AddToCampaignParams; result: AddToCampaignResult }
  listCampaigns: { params: ListCampaignsParams; result: ListCampaignsResult }
  getCampaign: { params: GetCampaignParams; result: GetCampaignResult }
  updateCampaign: { params: UpdateCampaignParams; result: UpdateCampaignResult }
  pauseCampaign: { params: PauseCampaignParams; result: PauseCampaignResult }
  activateCampaign: { params: ActivateCampaignParams; result: ActivateCampaignResult }
  getCampaignAnalytics: { params: GetCampaignAnalyticsParams; result: GetCampaignAnalyticsResult }
  getStepAnalytics: { params: GetStepAnalyticsParams; result: GetStepAnalyticsResult }
  bulkAddLeads: { params: BulkAddLeadsParams; result: BulkAddLeadsResult }
  getAccountHealth: { params: GetAccountHealthParams; result: GetAccountHealthResult }
  createInboxTest: { params: CreateInboxTestParams; result: CreateInboxTestResult }
  createCampaign: { params: CreateCampaignParams; result: CreateCampaignResult }
  getDailyCampaignAnalytics: { params: GetDailyCampaignAnalyticsParams; result: GetDailyCampaignAnalyticsResult }
  listLeads: { params: ListLeadsParams; result: ListLeadsResult }
  bulkDeleteLeads: { params: BulkDeleteLeadsParams; result: BulkDeleteLeadsResult }
  deleteCampaign: { params: DeleteCampaignParams; result: DeleteCampaignResult }
  patchLead: { params: PatchLeadParams; result: PatchLeadResult }
}

// ---------------------------------------------------------------------------
// Anymailfinder (integration adapter, 4 methods)
// ---------------------------------------------------------------------------

export type AnymailfinderToolMap = {
  findCompanyEmail: { params: FindCompanyEmailParams; result: FindCompanyEmailResult }
  findPersonEmail: { params: FindPersonEmailParams; result: FindPersonEmailResult }
  findDecisionMakerEmail: { params: FindDecisionMakerEmailParams; result: FindDecisionMakerEmailResult }
  verifyEmail: { params: VerifyEmailParams; result: VerifyEmailResult }
}

// ---------------------------------------------------------------------------
// Tomba (integration adapter, 3 methods)
// ---------------------------------------------------------------------------

export type TombaToolMap = {
  emailFinder: { params: EmailFinderParams; result: EmailFinderResult }
  domainSearch: { params: DomainSearchParams; result: DomainSearchResult }
  emailVerifier: { params: EmailVerifierParams; result: EmailVerifierResult }
}

// ---------------------------------------------------------------------------
// MillionVerifier (integration adapter, 2 methods)
// ---------------------------------------------------------------------------

export type MillionVerifierToolMap = {
  verifyEmail: { params: MillionVerifierVerifyEmailParams; result: MillionVerifierVerifyEmailResult }
  checkCredits: { params: MillionVerifierCheckCreditsParams; result: MillionVerifierCheckCreditsResult }
}

// ---------------------------------------------------------------------------
// ClickUp (integration adapter, 2 methods)
// ---------------------------------------------------------------------------

export type ClickUpToolMap = {
  verify: { params: ClickUpVerifyParams; result: ClickUpVerifyResult }
  createTask: { params: ClickUpCreateTaskParams; result: ClickUpCreateTaskResult }
}

// ---------------------------------------------------------------------------
// Lead (platform tool, 56 methods)
// ---------------------------------------------------------------------------

export type LeadToolMap = {
  // List operations
  listLists: { params: Record<string, never>; result: AcqList[] }
  createList: { params: Omit<CreateListParams, 'organizationId'>; result: AcqList }
  updateList: { params: { id: string } & UpdateListParams; result: AcqList }
  deleteList: { params: { id: string }; result: void }
  addContactsToList: { params: Omit<AddContactsToListParams, 'organizationId'>; result: AddContactsToListResult }
  addCompaniesToList: { params: Omit<AddCompaniesToListParams, 'organizationId'>; result: AddCompaniesToListResult }
  updateCompanyStage: {
    params: Omit<UpdateCompanyStageParams, 'organizationId'>
    result: void
  }
  updateContactStage: {
    params: Omit<UpdateContactStageParams, 'organizationId'>
    result: void
  }
  clearCompanyStages: {
    params: Omit<ClearCompanyStagesParams, 'organizationId'>
    result: void
  }
  clearContactStages: {
    params: Omit<ClearContactStagesParams, 'organizationId'>
    result: void
  }
  // Company operations
  createCompany: { params: Omit<CreateCompanyParams, 'organizationId'>; result: AcqCompany }
  upsertCompany: { params: Omit<UpsertCompanyParams, 'organizationId'>; result: AcqCompany }
  updateCompany: { params: { id: string } & UpdateCompanyParams; result: AcqCompany }
  getCompany: { params: { id: string }; result: AcqCompany | null }
  listCompanies: { params: CompanyFilters; result: AcqCompany[] }
  deleteCompany: { params: { id: string }; result: void }
  // Contact operations
  createContact: { params: Omit<CreateContactParams, 'organizationId'>; result: AcqContact }
  upsertContact: { params: Omit<UpsertContactParams, 'organizationId'>; result: AcqContact }
  updateContact: { params: { id: string } & UpdateContactParams; result: AcqContact }
  getContact: { params: { id: string }; result: AcqContact | null }
  getContactByEmail: { params: { email: string }; result: AcqContact | null }
  listContacts: {
    params: ContactFilters & { limit?: number; offset?: number }
    result: PaginatedResult<AcqContact>
  }
  deleteContact: { params: { id: string }; result: void }
  bulkImportContacts: { params: Omit<BulkImportParams, 'organizationId'>; result: BulkImportResult }
  bulkImportCompanies: {
    params: Omit<BulkImportCompaniesParams, 'organizationId'>
    result: BulkImportCompaniesResult
  }
  deactivateContactsByCompany: {
    params: { companyId: string }
    result: { deactivated: number }
  }
  // Deal operations
  upsertDeal: { params: Omit<UpsertDealParams, 'organizationId'>; result: AcqDeal }
  getDealByEmail: { params: { email: string }; result: AcqDeal | null }
  getDealByEnvelopeId: { params: { envelopeId: string }; result: AcqDeal | null }
  updateDealEnvelopeId: { params: { dealId: string; envelopeId: string }; result: AcqDeal | null }
  getDealById: { params: Omit<GetDealByIdParams, 'organizationId'>; result: AcqDeal | null }
  getContactById: { params: Omit<GetContactByIdParams, 'organizationId'>; result: AcqContact | null }
  getCompanyById: { params: Omit<GetCompanyByIdParams, 'organizationId'>; result: AcqCompany | null }
  // Deal-sync operations
  updateDiscoveryData: { params: Omit<UpdateDiscoveryDataParams, 'organizationId'>; result: void }
  updateProposalData: { params: Omit<UpdateProposalDataParams, 'organizationId'>; result: void }
  markProposalSent: { params: Omit<MarkProposalSentParams, 'organizationId'>; result: void }
  markProposalReviewed: { params: Omit<MarkProposalReviewedParams, 'organizationId'>; result: void }
  updateCloseLostReason: { params: Omit<UpdateCloseLostReasonParams, 'organizationId'>; result: void }
  updateFees: { params: Omit<UpdateFeesParams, 'organizationId'>; result: void }
  cacheInstantlyThreadIds: { params: Omit<CacheInstantlyThreadIdsParams, 'organizationId'>; result: void }
  transitionItem: { params: Omit<TransitionItemParams, 'organizationId'>; result: void }
  setContactNurture: { params: Omit<SetContactNurtureParams, 'organizationId'>; result: void }
  cancelSchedulesAndHitlByEmail: {
    params: Omit<CancelSchedulesAndHitlByEmailParams, 'organizationId'>
    result: { schedulesCancelled: number; hitlDeleted: number }
  }
  cancelHitlByDealId: { params: Omit<CancelHitlByDealIdParams, 'organizationId'>; result: { hitlDeleted: number } }
  clearDealFields: { params: Omit<ClearDealFieldsParams, 'organizationId'>; result: void }
  deleteDeal: { params: Omit<DeleteDealParams, 'organizationId'>; result: void }
  recordDealActivity: {
    params: Omit<RecordDealActivityParams, 'organizationId'>
    result: void
  }
  // Deal note operations
  createDealNote: {
    params: Omit<CreateDealNoteParams, 'organizationId'>
    result: AcqDealNote
  }
  listDealNotes: {
    params: Omit<ListDealNotesParams, 'organizationId'>
    result: AcqDealNote[]
  }
  // Deal task operations
  createDealTask: {
    params: Omit<CreateDealTaskParams, 'organizationId'>
    result: AcqDealTask
  }
  listDealTasks: {
    params: Omit<ListDealTasksParams, 'organizationId'>
    result: AcqDealTask[]
  }
  listDealTasksDue: {
    params: Omit<ListDealTasksDueParams, 'organizationId'>
    result: AcqDealTask[]
  }
  completeDealTask: {
    params: Omit<CompleteDealTaskParams, 'organizationId'>
    result: AcqDealTask
  }
  // Deal query & analytics operations
  listDeals: { params: DealFilters; result: AcqDeal[] }
  getDealPipelineAnalytics: { params: { recentLimit?: number }; result: DealPipelineAnalytics }
  // Enrichment data operations
  mergeEnrichmentData: {
    params: { id: string; table: 'acq_companies' | 'acq_contacts'; data: Record<string, unknown> }
    result: void
  }
  // Social monitoring operations
  upsertSocialPosts: {
    params: { posts: Omit<UpsertSocialPostParams, 'organizationId'>[] }
    result: UpsertSocialPostsResult
  }
  setDealStateKey: {
    params: {
      dealId: string
      stateKey: string
    }
    result: { ok: true }
  }
  // CRM workflow helpers
  transitionDeal: {
    params: {
      dealId: string
      toStage: string
      toState?: string
    }
    result: { deal: AcqDeal }
  }
  loadDeal: {
    params: { dealId: string }
    result: DealDetail | null
  }
}

// ---------------------------------------------------------------------------
// List (platform tool, 4 methods)
// ---------------------------------------------------------------------------

export type ListToolMap = {
  getConfig: {
    params: { listId: string }
    result: {
      scrapingConfig: ScrapingConfig
      icp: IcpRubric
      pipelineConfig: PipelineConfig & { dataMode: 'mock' | 'live' }
    }
  }
  recordExecution: {
    params: Omit<RecordListExecutionParams, 'organizationId'>
    result: void
  }
  updateCompanyStage: {
    params: Omit<UpdateCompanyStageParams, 'organizationId'>
    result: void
  }
  updateContactStage: {
    params: Omit<UpdateContactStageParams, 'organizationId'>
    result: void
  }
  clearCompanyStages: {
    params: Omit<ClearCompanyStagesParams, 'organizationId'>
    result: void
  }
  clearContactStages: {
    params: Omit<ClearContactStagesParams, 'organizationId'>
    result: void
  }
  listPendingCompanyIds: {
    params: Omit<ListPendingCompanyIdsParams, 'organizationId'>
    result: string[]
  }
  listPendingContactIds: {
    params: Omit<ListPendingContactIdsParams, 'organizationId'>
    result: string[]
  }
}

// ---------------------------------------------------------------------------
// PDF (platform tool, 2 methods)
// ---------------------------------------------------------------------------

export type PdfToolMap = {
  render: {
    params: {
      document: Record<string, unknown>
      theme?: Record<string, unknown>
      storage: { bucket: string; path: string }
    }
    result: { success: boolean; pdfUrl: string; size: number }
  }
  renderToBuffer: {
    params: {
      document: Record<string, unknown>
      theme?: Record<string, unknown>
    }
    result: { buffer: string }
  }
}

// ---------------------------------------------------------------------------
// Approval (platform tool, 2 methods)
// ---------------------------------------------------------------------------

export type ApprovalToolMap = {
  create: {
    params: {
      actions: Array<{
        id: string
        label: string
        type: 'primary' | 'secondary' | 'danger' | 'outline'
        icon?: string
        color?: string
        target?: { resourceType: 'agent' | 'workflow'; resourceId: string; sessionId?: string }
        form?: Record<string, unknown>
        requiresConfirmation?: boolean
        confirmationMessage?: string
        description?: string
      }>
      context: Record<string, unknown>
      description?: string
      priority?: number
      humanCheckpoint?: string
      metadata?: Record<string, unknown>
      expiresAt?: string
      idempotencyKey?: string
    }
    result: { id: string }
  }
  deleteByMetadata: {
    params: { metadata: Record<string, unknown>; status?: string }
    result: { deleted: number }
  }
}

// ---------------------------------------------------------------------------
// Execution (platform tool, 1 method)
// ---------------------------------------------------------------------------

export type ExecutionToolMap = {
  trigger: {
    params: { resourceId: string; input?: unknown }
    result: { success: boolean; executionId: string; output: unknown; error?: string }
  }
  triggerAsync: {
    params: { resourceId: string; input?: unknown }
    result: { executionId: string }
  }
}

// ---------------------------------------------------------------------------
// Email (platform tool, 1 method)
// ---------------------------------------------------------------------------

export type EmailToolMap = {
  send: {
    params: {
      subject: string
      html?: string
      text?: string
      replyTo?: string
      tags?: Array<{ name: string; value: string }>
    } & (
      | { userIds: string[]; targetRole?: never; targetAll?: never }
      | { targetRole: string; userIds?: never; targetAll?: never }
      | { targetAll: true; userIds?: never; targetRole?: never }
    )
    result: { sent: number; failed: number; errors?: Array<{ userId: string; email: string; error: string }> }
  }
}

// ---------------------------------------------------------------------------
// Aggregate platform adapter contract
// ---------------------------------------------------------------------------

/**
 * Platform tools that have SDK adapter method maps and are dispatched by the
 * API parent process without worker-owned credentials.
 */
export type PlatformToolMapByName = {
  email: EmailToolMap
  storage: StorageToolMap
  pdf: PdfToolMap
  notification: NotificationToolMap
  approval: ApprovalToolMap
  scheduler: SchedulerToolMap
  acqDb: LeadToolMap
  crm: CrmToolMap
  projects: ProjectsToolMap
  list: ListToolMap
  execution: ExecutionToolMap
}

export type PlatformToolName = keyof PlatformToolMapByName

export type PlatformToolMethod<TTool extends PlatformToolName> = Extract<keyof PlatformToolMapByName[TTool], string>

type PlatformToolEntry<
  TTool extends PlatformToolName,
  TMethod extends PlatformToolMethod<TTool>
> = PlatformToolMapByName[TTool][TMethod] extends MethodEntry ? PlatformToolMapByName[TTool][TMethod] : never

export type PlatformToolParams<
  TTool extends PlatformToolName,
  TMethod extends PlatformToolMethod<TTool>
> = PlatformToolEntry<TTool, TMethod>['params']

export type PlatformToolResult<
  TTool extends PlatformToolName,
  TMethod extends PlatformToolMethod<TTool>
> = PlatformToolEntry<TTool, TMethod>['result']
