/**
 * CYBERVIEWER SCENARIO TYPE DEFINITIONS
 *
 * This file defines the EXACT structure expected by the parser.
 * AI-generated JSON MUST conform to these types.
 *
 * Schema Source: src/shared/schemas/scenario.schema.ts
 * Version: 3.0
 */

// ============================================================================
// PRIMITIVES
// ============================================================================

interface Position {
  x: number;
  y: number;
}

interface Viewport {
  zoom: number;
  pan: Position;
}

interface MitreMetadata {
  id: string;        // Format: "T1234" or "T1234.001"
  tactic: string;    // e.g. "Initial Access", "Credential Access"
  technique: string; // e.g. "Supply Chain Compromise", "Unsecured Credentials"
}

// ============================================================================
// ICON REGISTRY (EXHAUSTIVE)
// ============================================================================

/**
 * CRITICAL: Use ONLY these exact keys. No custom icons allowed.
 * Parser will fall back to IconDefault for invalid keys.
 * These are logical registry keys, not SVG filenames and not iconPath values.
 * Read Icon-Catalog.md for the human-readable selection guide.
 */
type IconKey =
  // Actors & Roles
  | 'IconKali'
  | 'IconAttacker'
  | 'IconHacker'      // Alias for IconAttacker
  | 'IconUser'
  | 'IconAttackerAlt'
  | 'IconVictim'

  // Infrastructure & Devices
  | 'IconServer'
  | 'IconWorkstation'
  | 'IconCloud'
  | 'IconNetwork'
  | 'IconFirewall'
  | 'IconRouter'
  | 'IconWindows'
  | 'IconLinux'
  | 'IconMobile'
  | 'IconAWS'
  | 'IconAzure'
  | 'IconGoogle'
  | 'IconLambda'
  | 'IconMetadata'
  | 'IconDC'
  | 'IconMachine'
  | 'IconWinServer'
  | 'IconVPN'
  | 'IconWAF'
  | 'IconActiveDirectory'

  // Developer Tools & Supply Chain
  | 'IconGit'
  | 'IconGitHub'
  | 'IconNpm'
  | 'IconDocker'
  | 'IconPipeline'
  | 'IconAPI'
  | 'IconBucket'
  | 'IconPackage'
  | 'IconKubernetes'
  | 'IconBrowser'

  // System Components
  | 'IconProcess'
  | 'IconService'
  | 'IconTerminal'
  | 'IconMemory'
  | 'IconDatabase'
  | 'IconMSSQL'
  | 'IconMySQL'
  | 'IconPostgreSQL'
  | 'IconEnv'
  | 'IconFolder'
  | 'IconCode'
  | 'IconData'
  | 'IconKernel'
  | 'IconRegistry'
  | 'IconScheduler'
  | 'IconVariable'
  | 'IconPowerShell'

  // Secrets & Credentials
  | 'IconCredential'
  | 'IconKey'
  | 'IconToken'
  | 'IconCertificate'
  | 'IconTicket'
  | 'IconHash'
  | 'IconCreds'
  | 'IconMFA'

  // Network & Communication
  | 'IconDNS'
  | 'IconSocks'
  | 'IconEmail'
  | 'IconSlack'
  | 'IconTeams'
  | 'IconDiscord'
  | 'IconMail'
  | 'IconWeb'

  // Actions & Events
  | 'IconSearch'
  | 'IconDownload'
  | 'IconUpload'
  | 'IconInject'
  | 'IconExploit'
  | 'IconPenetrationTool'
  | 'IconLock'
  | 'IconAlert'
  | 'IconCheck'
  | 'IconBurpSuite'
  | 'IconMetasploit'

  // Threats & Malware
  | 'IconMalware'
  | 'IconC2'
  | 'IconBackdoor'
  | 'IconEDR'
  | 'IconCobaltStrike'

  // Infected Variants (Compromised)
  | 'IconInfectedCode'
  | 'IconInfectedProcess'
  | 'IconInfectedTerminal'
  | 'IconInfectedService'
  | 'IconInfectedPackage'
  | 'IconInfectedPipeline'
  | 'IconInfectedDocker'
  | 'IconInfectedScheduler'

  // Stolen Variants (Exfiltrated)
  | 'IconStolenToken'
  | 'IconStolenKey'
  | 'IconStolenCredential'
  | 'IconStolenCertificate'
  | 'IconStolenDatabase'

  // Brands / Organizations
  | 'IconFortiGate'
  | 'IconFortiPAM'
  | 'IconFortiDeceptor'
  | 'IconFortiSIEM'
  | 'IconSKTelecom'

  // Fallback
  | 'IconDefault';

// ============================================================================
// ENTITIES
// ============================================================================

/**
 * Base fields common to all entity types
 */
interface BaseEntity {
  id: string;              // Unique identifier (snake_case recommended)
  label: string;           // Human-readable display name
  position?: Position;     // Optional: Canvas coordinates (auto-layout if omitted)
  icon?: IconKey;          // Optional: Exact IconKey only. Omit if unsure. Never use filenames or iconPath.
}

/**
 * Node Entity - Basic graph node (servers, users, processes, files)
 */
interface NodeEntity extends BaseEntity {
  type: 'node';
}

/**
 * Container Entity - Groups related entities
 *
 * Containers represent ANY logical boundary or grouping:
 * 1. Network Boundaries (DMZ, corporate network, cloud VPC)
 * 2. System Internals (processes/files inside ONE machine)
 * 3. Operational Environments (attacker's toolkit, C2 infrastructure)
 * 4. Functional Groupings (CI/CD pipeline, auth system, kernel subsystem)
 *
 * CRITICAL: Use 'members' array to specify children (NOT parent pointers).
 * Parser converts members[] to parent relationships for Cytoscape.
 *
 * Examples:
 * - Network: "corporate_network" containing servers/workstations
 * - System: "victim_laptop" containing browser/terminal/malware
 * - Environment: "attacker_infrastructure" containing tools/proxies/data
 * - Functional: "build_pipeline" containing CI/build/deploy components
 */
interface ContainerEntity extends BaseEntity {
  type: 'container';
  width?: number;          // Container width in pixels (default: auto)
  height?: number;         // Container height in pixels (default: auto)
  style?: string;          // e.g. "dashed_border"
  color?: string;          // Border color hex (e.g. "#3b82f6") - optional
  members: string[];       // Array of child entity IDs (REQUIRED, min 1)
}

/**
 * TextBox Entity - Narrative annotations or alerts
 */
interface TextBoxEntity extends BaseEntity {
  type: 'text_box';
}

/**
 * Discriminated union of all entity types
 */
type ScenarioEntity = NodeEntity | ContainerEntity | TextBoxEntity;

// ============================================================================
// VISIBILITY
// ============================================================================

/**
 * Visibility range for entity-keyed format
 */
interface VisibilityRange {
  start: number; // First step where entity appears (inclusive)
  end: number;   // Last step where entity is visible (inclusive)
}

/**
 * CRITICAL VISIBILITY FORMAT:
 *
 * Schema expects ENTITY-KEYED format:
 * {
 *   "entity_id": { "start": 0, "end": 100 }
 * }
 *
 * NOT step-keyed format:
 * {
 *   "0": ["entity1", "entity2"]  // ❌ WRONG - Will fail validation
 * }
 *
 * Omitted entities are ALWAYS visible.
 */
type VisibilityMap = Record<string, VisibilityRange>;

// ============================================================================
// TIMELINE STEPS
// ============================================================================

/**
 * Edge Step - Represents data flow or action between entities
 *
 * CRITICAL: Direction represents DATA FLOW, not who initiates.
 * - Download: from=server, to=client
 * - Upload: from=client, to=server
 * - Exfiltration: from=malware, to=c2
 */
interface EdgeStep {
  id: number;              // Step number (starts at 1, NOT 0)
  type: 'edge';
  name: string;            // Action label (e.g. "Download malicious package")
  from: string;            // Source entity ID
  to: string;              // Target entity ID
  icon?: IconKey;          // Optional: Icon that animates along the edge
  tooltip?: string;        // Optional: Detailed technical explanation
  cli?: string;            // Optional: Command line instruction
  description?: string;    // Optional: Step description
  mitre?: MitreMetadata;   // Optional: MITRE ATT&CK mapping
}

/**
 * ShowText Step - Displays narrative text or highlights an entity
 */
interface ShowTextStep {
  id: number;              // Step number (starts at 1, NOT 0)
  type: 'show_text';
  name: string;            // Event label
  target_entity: string;   // ID of text_box or entity to highlight
  content: string;         // Text message to display
  style?: string;          // Optional: e.g. "warning_alert", "info_toast"
  mitre?: MitreMetadata;   // Optional: MITRE ATT&CK mapping
}

/**
 * Discriminated union of all step types
 */
type TimelineStep = EdgeStep | ShowTextStep;

// ============================================================================
// METADATA (EXTENDED LLM OUTPUT)
// ============================================================================

/**
 * Rich metadata for enhanced UI display (v3.0 feature)
 */
interface ScenarioMetadata {
  /**
   * Full HTML description for details panel
   *
   * CRITICAL: Use SINGLE QUOTES for HTML attributes to avoid JSON escaping:
   * ✅ <span style='color:#ef4444'>Tool</span>
   * ❌ <span style="color:#ef4444">Tool</span>  // Requires escaping
   */
  descriptionHtml?: string;

  /**
   * Copy-paste ready CLI commands with comments
   *
   * Format:
   * # Step 1: Description
   * $ command --flags target
   *
   * CRITICAL: Use SINGLE QUOTES in commands to avoid escaping:
   * ✅ curl -d 'payload' url
   * ❌ curl -d "payload" url  // Requires escaping
   */
  commandsBlock?: string;

  /**
   * External references (tools, CVEs, docs, repos)
   * Examples:
   * - "Impacket - /usr/bin/impacket-ntlmrelayx"
   * - "GitHub - https://github.com/fortra/impacket"
   * - "CVE-2021-34527 - PrintNightmare"
   */
  extraInfo?: string[];

  /**
   * Attack requirements/preconditions
   * Examples:
   * - "Target must have SMB Signing disabled"
   * - "Attacker must be on same network"
   */
  prerequisites?: string[];

  /**
   * What attacker achieves
   * Examples:
   * - "Lateral Movement without passwords"
   * - "Remote Code Execution (RCE)"
   */
  attackerGains?: string[];

  /**
   * Detection indicators / OPSEC notes
   * Examples:
   * - "Monitor NTLM logins from unexpected IPs"
   * - "Network traffic spikes on ports 139/445"
   */
  detectionNotes?: string[];

  /**
   * MITRE ATT&CK technique IDs
   * Format: ["T1558.004", "T1110.002"]
   */
  mitreCategories?: string[];

  /**
   * OWASP categories (if applicable)
   */
  owaspCategories?: string[];
}

// ============================================================================
// ROOT SCENARIO
// ============================================================================

/**
 * Complete attack scenario structure
 *
 * This is the TOP-LEVEL object AI must output.
 */
interface Scenario {
  // REQUIRED FIELDS
  title: string;                    // Attack scenario title
  version: '3.0';                   // MUST be exactly "3.0"
  entities: ScenarioEntity[];       // All nodes, containers, text boxes
  steps: TimelineStep[];            // Chronological actions (start at id=1)

  // OPTIONAL FIELDS
  description?: string;             // Brief 1-2 sentence overview
  shortDescription?: string;        // Ultra-brief (7 words max)
  tags?: string[];                  // Categorization tags (see guidelines)
  viewport?: Viewport;              // Initial camera position
  visibility?: VisibilityMap;       // When entities appear/disappear
  metadata?: ScenarioMetadata;      // Rich v3.0 metadata
}

// ============================================================================
// EXPORTS
// ============================================================================

/**
 * This is what AI outputs:
 * A single JSON object conforming to the Scenario interface.
 */
export type { Scenario };
