// Shared types and constants for all extension contexts (background, content,
// options, popup). This is the single source of truth for the message contract
// and the storage schema.

// Extra parameters for the 'prompt' (prompt-engineer) action. All optional;
// omitted / 'Auto' means the prompt engineer decides from the input itself.
export interface PromptParams {
  pattern?: string;  // see PROMPT_PATTERNS in actions.ts
  persona?: string;  // preset from PROMPT_PERSONAS, or free text (Custom)
  format?: string;   // see PROMPT_FORMATS
}

export interface AnalyzePayload {
  text: string;
  action: string;
  style?: string;
  promptParams?: PromptParams;
  // Per-request model override (e.g. Prompt Builder's model picker). Falls
  // back to the configured model when absent.
  model?: string;
}

export interface LexAIConfig {
  provider?: string;
  apiKey?: string; // legacy plaintext key — kept for backward compat until migrated
  apiKeyEnc?: string; // base64(nonce + secretbox ciphertext)
  encKey?: string; // base64 32-byte secretbox key
  model?: string;
  // Which provider the stored key was entered for. `provider` can change on its
  // own (Options saves provider/model without touching an existing key), so
  // without this the key silently gets sent to a provider that will reject it.
  // Absent for keys saved by builds before this field existed.
  keyProvider?: string;
}

export interface LexAIResponse {
  result?: string;
  error?: string;
}

// Storage keys the background worker reads when resolving provider config.
export const CONFIG_STORAGE_KEYS = ['provider', 'apiKey', 'apiKeyEnc', 'encKey', 'model', 'keyProvider'] as const;

// ─── Message contract ─────────────────────────────────────────────────────────
// ANALYZE_TEXT intentionally supports BOTH shapes:
//   { type, payload: { text, action, style } }  (content script, popup)
//   { type, text, action, style }               (flat/legacy)
// The background handler normalizes; both must keep working.

export interface AnalyzeTextMessage {
  type: 'ANALYZE_TEXT';
  payload?: AnalyzePayload;
  text?: string;
  action?: string;
  style?: string;
  promptParams?: PromptParams;
  model?: string;
}

export interface CopyAsMessage {
  type: 'COPY_AS';
  text: string;
  format: string;
}

export interface ListModelsMessage {
  type: 'LIST_MODELS';
  provider?: string;
  // Freshly typed key not yet saved — preferred over the stored key when present.
  apiKey?: string;
}

export type LexAIMessage = AnalyzeTextMessage | CopyAsMessage | ListModelsMessage;
