/**
 * Batch builder & storage layer contract types.
 *
 * Defines all types for the LLM-powered Batch Builder, plugin system,
 * storage management, and data source connectors.
 *
 * @see AI_REFACTOR_PLAN.md — Phase 0, Step 0.1
 */
import { z } from 'zod';

// ---------------------------------------------------------------------------
// Storage
// ---------------------------------------------------------------------------

export const StorageTargetSchema = z.enum(['local', 'cloud', 'sync', 'none']);
export type StorageTarget = z.infer<typeof StorageTargetSchema>;

export const BatchStorageSchema = z.object({
  /** Where structured records are persisted. */
  records: StorageTargetSchema,
  /** Where vector embeddings are stored. */
  vectors: StorageTargetSchema,
  /** Where raw/unprocessed data is kept. */
  rawData: StorageTargetSchema,
});
export type BatchStorage = z.infer<typeof BatchStorageSchema>;

// ---------------------------------------------------------------------------
// Connectors
// ---------------------------------------------------------------------------

export const ConnectorTypeSchema = z.enum([
  'imap',
  'filesystem',
  'calendar',
  'api',
  'gmail',
  'gdrive',
  'outlook',
]);
export type ConnectorType = z.infer<typeof ConnectorTypeSchema>;

// ---------------------------------------------------------------------------
// Batch Config Building Blocks
// ---------------------------------------------------------------------------

export const BatchActionTypeSchema = z.enum([
  'create_record',
  'update_record',
  'delete_record',
  'index_document',
  'send_notification',
  'call_agent',
]);
export type BatchActionType = z.infer<typeof BatchActionTypeSchema>;

export const BatchSourceSchema = z.object({
  connector: ConnectorTypeSchema,
  config: z.record(z.string(), z.unknown()),
});
export type BatchSource = z.infer<typeof BatchSourceSchema>;

export const BatchTriggerSchema = z.object({
  type: z.enum(['cron', 'event']),
  /** Cron expression (required when `type === 'cron'`). */
  schedule: z.string().optional(),
  /** IANA timezone identifier. Defaults to system timezone when omitted. */
  timezone: z.string().optional(),
});
export type BatchTrigger = z.infer<typeof BatchTriggerSchema>;

export const BatchAnalysisSchema = z.object({
  /** Natural-language prompt describing what to extract / classify / summarise. */
  prompt: z.string(),
  /** Override the default LLM model for this analysis step. */
  modelOverride: z.string().optional(),
  /** Optional JSON Schema describing the expected output shape. */
  outputSchema: z.record(z.string(), z.unknown()).optional(),
});
export type BatchAnalysis = z.infer<typeof BatchAnalysisSchema>;

export const BatchActionSchema = z.object({
  type: BatchActionTypeSchema,
  /** Target table for record operations. */
  table: z.string().optional(),
  /** Field mapping from analysis output keys → table columns / action parameters. */
  mapping: z.record(z.string(), z.string()).optional(),
});
export type BatchAction = z.infer<typeof BatchActionSchema>;

// ---------------------------------------------------------------------------
// Full Batch Config
// ---------------------------------------------------------------------------

export const BatchConfigSchema = z.object({
  id: z.string(),
  name: z.string(),
  description: z.string(),
  enabled: z.boolean(),
  source: BatchSourceSchema,
  trigger: BatchTriggerSchema,
  analysis: BatchAnalysisSchema,
  actions: z.array(BatchActionSchema),
  storage: BatchStorageSchema,
  /** Permission scopes this batch requires. Validated against PermissionManager at runtime. */
  permissions: z.array(z.string()),
});
export type BatchConfig = z.infer<typeof BatchConfigSchema>;

// ---------------------------------------------------------------------------
// Batch Runtime
// ---------------------------------------------------------------------------

export const BatchStatusSchema = z.enum(['idle', 'running', 'error', 'disabled']);
export type BatchStatus = z.infer<typeof BatchStatusSchema>;

export const BatchRunResultSchema = z.object({
  batchId: z.string(),
  runAt: z.string().datetime(),
  status: BatchStatusSchema,
  itemsProcessed: z.number().int(),
  errors: z.array(z.string()),
});
export type BatchRunResult = z.infer<typeof BatchRunResultSchema>;

// ---------------------------------------------------------------------------
// Data Manager
// ---------------------------------------------------------------------------

export const DataSourceInfoSchema = z.object({
  type: ConnectorTypeSchema,
  label: z.string(),
  recordCount: z.number().int().min(0),
  sizeBytes: z.number().int().min(0),
  storageTarget: StorageTargetSchema,
});
export type DataSourceInfo = z.infer<typeof DataSourceInfoSchema>;

export const StorageStatsSchema = z.object({
  localUsedBytes: z.number().int().min(0),
  cloudUsedBytes: z.number().int().min(0),
  cloudLimitBytes: z.number().int().min(0),
  sources: z.array(DataSourceInfoSchema),
});
export type StorageStats = z.infer<typeof StorageStatsSchema>;
