/**
 * Performance Profiling Types — Remote Diagnostics Phase 4
 * CPU/Memory profiling for iOS, Android, and Web.
 */

import { z } from 'zod';

// ─────────────────────────────────────────────────────────────────────────────
// Profile Types
// ─────────────────────────────────────────────────────────────────────────────

export const ProfileTypeEnum = z.enum(['cpu', 'memory', 'battery', 'network', 'render']);
export type ProfileType = z.infer<typeof ProfileTypeEnum>;

export const PlatformEnum = z.enum(['ios', 'android', 'web']);
export type ProfilePlatform = z.infer<typeof PlatformEnum>;

// ─────────────────────────────────────────────────────────────────────────────
// CPU Profile
// ─────────────────────────────────────────────────────────────────────────────

export interface CPUProfileSample {
  timestamp: number; // milliseconds since profile start
  threadId: string;
  threadName?: string;
  cpuUsagePercent: number; // 0-100
  callStack?: string[]; // Function/method names in stack
}

export interface CPUProfile {
  type: 'cpu';
  platform: ProfilePlatform;
  samples: CPUProfileSample[];
  durationMs: number;
  samplingIntervalMs: number;
  threads: Array<{
    id: string;
    name: string;
    avgCpuPercent: number;
    maxCpuPercent: number;
  }>;
}

// ─────────────────────────────────────────────────────────────────────────────
// Memory Profile
// ─────────────────────────────────────────────────────────────────────────────

export interface MemoryProfileSample {
  timestamp: number;
  usedBytes: number;
  totalBytes: number;
  heapBytes?: number;
  stackBytes?: number;
  nativeBytes?: number; // For React Native / hybrid apps
  objectCounts?: Record<string, number>; // Class name -> instance count
}

export interface MemoryProfile {
  type: 'memory';
  platform: ProfilePlatform;
  samples: MemoryProfileSample[];
  durationMs: number;
  samplingIntervalMs: number;
  peakUsageBytes: number;
  leakSuspects?: Array<{
    className: string;
    instanceCount: number;
    growthRate: number; // instances per minute
  }>;
}

// ─────────────────────────────────────────────────────────────────────────────
// Battery Profile
// ─────────────────────────────────────────────────────────────────────────────

export interface BatteryProfileSample {
  timestamp: number;
  level: number; // 0-100
  state: 'charging' | 'discharging' | 'full' | 'unknown';
  powerSource?: 'battery' | 'ac' | 'usb' | 'wireless';
  estimatedTimeRemaining?: number; // minutes
  temperature?: number; // celsius (Android only)
}

export interface BatteryProfile {
  type: 'battery';
  platform: ProfilePlatform;
  samples: BatteryProfileSample[];
  durationMs: number;
  samplingIntervalMs: number;
  drainRatePerHour: number; // percentage per hour
}

// ─────────────────────────────────────────────────────────────────────────────
// Network Profile
// ─────────────────────────────────────────────────────────────────────────────

export interface NetworkProfileSample {
  timestamp: number;
  bytesSent: number;
  bytesReceived: number;
  requestsCount: number;
  errorsCount: number;
  latencyAvg: number; // ms
  latencyMax: number; // ms
}

export interface NetworkProfile {
  type: 'network';
  platform: ProfilePlatform;
  samples: NetworkProfileSample[];
  durationMs: number;
  samplingIntervalMs: number;
  totalBytesSent: number;
  totalBytesReceived: number;
  totalRequests: number;
  totalErrors: number;
}

// ─────────────────────────────────────────────────────────────────────────────
// Render Profile (Frame times)
// ─────────────────────────────────────────────────────────────────────────────

export interface RenderProfileSample {
  timestamp: number;
  frameTimeMs: number;
  droppedFrames: number;
  gpuTimeMs?: number;
  layoutTimeMs?: number;
  drawTimeMs?: number;
}

export interface RenderProfile {
  type: 'render';
  platform: ProfilePlatform;
  samples: RenderProfileSample[];
  durationMs: number;
  fps: number;
  frameDrops: number;
  avgFrameTimeMs: number;
  p95FrameTimeMs: number;
  p99FrameTimeMs: number;
}

// ─────────────────────────────────────────────────────────────────────────────
// Profile Document (stored in Cosmos)
// ─────────────────────────────────────────────────────────────────────────────

export type ProfileData = CPUProfile | MemoryProfile | BatteryProfile | NetworkProfile | RenderProfile;

export interface PerformanceProfileDoc {
  id: string;
  pk: string; // Composite: `${productId}:${sessionId}`
  sessionId: string;
  productId: string;

  // Profile metadata
  profileId: string;
  profileType: ProfileType;
  platform: ProfilePlatform;
  deviceInfo: {
    deviceModel: string;
    osVersion: string;
    appVersion: string;
    cpuCores?: number;
    totalMemoryBytes?: number;
  };

  // Profile data
  profile: ProfileData;

  // Timestamps
  startedAt: string;
  endedAt: string;
  createdAt: string;
  updatedAt?: string;

  // TTL
  ttl: number;
}

// ─────────────────────────────────────────────────────────────────────────────
// Input Schemas
// ─────────────────────────────────────────────────────────────────────────────

export const IngestProfileSchema = z.object({
  sessionId: z.string(),
  profileType: ProfileTypeEnum,
  platform: PlatformEnum,
  deviceInfo: z.object({
    deviceModel: z.string(),
    osVersion: z.string(),
    appVersion: z.string(),
    cpuCores: z.number().optional(),
    totalMemoryBytes: z.number().optional(),
  }),
  profile: z.record(z.unknown()), // ProfileData validated at runtime
});

export const QueryProfilesSchema = z.object({
  profileType: ProfileTypeEnum.optional(),
  platform: PlatformEnum.optional(),
  limit: z.coerce.number().min(1).max(50).default(10),
  continuationToken: z.string().optional(),
});

export type IngestProfileInput = z.infer<typeof IngestProfileSchema>;
export type QueryProfilesInput = z.infer<typeof QueryProfilesSchema>;

// ─────────────────────────────────────────────────────────────────────────────
// Profiling Configuration
// ─────────────────────────────────────────────────────────────────────────────

export interface ProfilingConfig {
  enabled: boolean;
  autoStart: boolean;

  // Profile types to capture
  cpu: {
    enabled: boolean;
    samplingIntervalMs: number;
    durationMs: number;
  };
  memory: {
    enabled: boolean;
    samplingIntervalMs: number;
    durationMs: number;
    trackObjectCounts: boolean;
  };
  battery: {
    enabled: boolean;
    samplingIntervalMs: number;
  };
  network: {
    enabled: boolean;
    samplingIntervalMs: number;
  };
  render: {
    enabled: boolean;
    samplingIntervalMs: number;
  };

  // Trigger conditions
  triggers: {
    onHighCPU: boolean; // Auto-profile when CPU > threshold
    cpuThreshold: number;
    onMemoryPressure: boolean; // Auto-profile on memory warning
    onLowBattery: boolean; // Auto-profile when battery < 20%
    onFrameDrops: boolean; // Auto-profile when frames drop
    frameDropThreshold: number;
  };
}

// ─────────────────────────────────────────────────────────────────────────────
// Profile Analysis Types
// ─────────────────────────────────────────────────────────────────────────────

export interface ProfileAnalysis {
  profileId: string;
  issues: Array<{
    severity: 'info' | 'warning' | 'critical';
    category: string;
    description: string;
    recommendation: string;
    evidence: Record<string, unknown>;
  }>;
  summary: {
    healthScore: number; // 0-100
    topIssues: string[];
    recommendations: string[];
  };
}
