# Mission Planner - MIDS Requirements

## Overview
The Mission Planner module enables users to create and manage cryptographic mission plans for secure communications over MIDS (Multifunction Information Distribution System) networks. It supports automatic linking between BTEK (Black Traffic Encryption Key) and WKEK (Multifunction Key Encryption Key) to simplify mission planning workflows.

## Features

### Mission Planning Grid
- Display multiple mission plan groups in a sortable grid format
- Each row represents a mission group with configurable cryptographic parameters
- Support for adding, removing, reordering, and duplicating mission groups
- Visual grouping of related cryptographic keys for each mission segment

### Automatic Key Linking
When a user selects a BTEK (Black Traffic Encryption Key), the system automatically:

1. **Detects BTEK Variant**: Identifies "BL" (Black) variant in the BTEK name (e.g., "USEAD BL123456 880091")
2. **Finds Matching WKEK**: Searches for the corresponding "KL" (Key Lock) variant WKEK (e.g., "USEAD KL123456 880091")
3. **Auto-Selects WKEK**: Automatically populates the WKEK short title field
4. **Populates WKEK Editions**: Queries the database and loads all available editions for the matched WKEK
5. **Matches Editions**: Auto-selects the WKEK edition that matches the BTEK edition name (e.g., BTEK "edition A" → WKEK "edition A")

### KS0 Edition Auto-Population
When a user selects a KS0 (Key Set Zero) short title:
- Queries the database for all editions matching the selected KS0 short title (KeyType=2)
- Includes the ShortTitle navigation property to ensure proper name matching
- Auto-selects the first available edition
- Updates date calculations and segment counts based on the selected edition

### Edition Synchronization
When a user changes the BTEK edition after auto-linking is established:
- The WKEK edition automatically updates to match the new BTEK edition by edition name
- If no exact match exists, the first available WKEK edition is selected

### Mission Group Configuration

Each mission group contains the following configurable parameters:

| Parameter | Description | Validates/Calculations |
|-----------|-------------|------------------------|
| **BTEK Short Title** | Black Traffic Encryption Key short title | Auto-populated from database filter (KeyType=6) |
| **BTEK Edition** | Specific edition of the selected BTEK | Auto-populates WKEK edition on change |
| **WKEK/WBKEK Short Title** | Multifunction Key short title | Auto-linked from BTEK ("BL" → "KL" mapping); auto-populates WKEK Editions dropdown on manual selection change |
| **WKEK/WBKEK Edition** | Specific edition of the selected WKEK | Auto-populated from database (KeyType=2) |
| **KS0 Short Title** | Key Set Zero short title | Optional, user-selected; auto-populates KS0 Editions dropdown on change |
| **KS0 Edition** | Specific edition of KS0 | Auto-populated from database (KeyType=2) when KS0 Short Title changes |
| **WII** | Waveform Instance Identifier | Must be exactly 9 characters; shows red validation warning if invalid |
| **Mission CVLL** | Cryptographic Verification List Level | Dropdown selection (R001-R127) |
| **Encryption Type** | Encryption algorithm selector | Dropdown with available algorithms |
| **Start Date** | Mission effective start date | Auto-calculated from editions (first group), or follows previous group (subsequent groups) |
| **End Date** | Mission effective end date | Last day of the start date's month |
| **BTEK Segment Start Day** | Day of month for BTEK segment start | Dropdown (1-31), auto-validates |
| **BTEK Segment Count** | Number of BTEK segments to transmit | Auto-calculated based on edition and start day |

### Date Calculation Logic

1. **First Mission Group**: When creating a new mission (single group):
   - Default to 1st of current month
   - End date is the last day of the start month
2. **Subsequent Mission Groups**: When adding a new group after existing groups:
   - Start date defaults to the first day of the month following the previous group's end date
   - For example: if Group 1 ends 5/31/2026, Group 2 defaults to 6/1/2026
3. **Edition Selection**: When editions are selected and no start date is set, the earliest edition effective date (normalized to first-of-month) is used as the default. If a start date is already set (manually or by default), it is preserved and not overwritten.
4. **Manual Start Date Change**: End date automatically recalculates to last day of selected start month
5. **Export Behavior**: The CD export uses each mission group's configured start date. User-set dates are preserved and not overwritten by edition effective dates.
6. **Date Validation**: Warns if selected BTEK, WKEK, and KS0 editions are from different months

### BTEK Segment Calculation

Based on:
- BTEK edition effective date (month/year)
- BTEK segment start day (1-31, default 1)
- Days in the edition's month

Formula: `SegmentCount = DaysInMonth - SegmentStartDay + 1` (capped at 31 segments max)

## User Interface

### Page Layout
- **Title Bar**: Mission Planner header with navigation
- **Mission Group Grid**: Vertical scrollable list of mission groups
  - Each group row displays all configuration controls
  - Up/Down arrows to reorder groups
  - Delete button to remove group
  - Duplicate button to clone group
- **Add Group Button**: Adds a new blank mission group at the bottom
- **Export Button**: Opens SDA Export dialog (separate feature)

### Controls per Mission Group

| Control | Type | Behavior |
|---------|------|----------|
| BTEK Short Title | Dropdown | Enables auto-linking to WKEK when "BL" variant selected |
| BTEK Edition | Dropdown | Auto-updates WKEK edition when changed |
| WKEK/WBKEK Short Title | Dropdown | Auto-linked from BTEK "BL" variant |
| WKEK/WBKEK Edition | Dropdown | Auto-populated from database (KeyType=2) when WKEK Short Title changes |
| KS0 Short Title | Dropdown | Optional, auto-populates KS0 Editions dropdown on change; only visible for Collins/Raytheon equipment |
| KS0 Edition | Dropdown | Auto-populated from database (KeyType=2) when KS0 Short Title changes; only visible for Collins/Raytheon equipment |
| WII | ComboBox (Edit + Dropdown) | Must be exactly 9 characters; shows red validation warning if invalid |
| Mission CVLL | Dropdown | R001-R127 |
| Encryption Type | Radio Buttons | Group-specific selection |
| Start Date | DatePicker | Auto-calculated, can be manually overridden |
| End Date | DatePicker | Auto-calculated, can be manually overridden |
| Segment Start Day | Dropdown | 1-31 integer |
| Segment Count | Label | Read-only, auto-calculated |

### Equipment Profile Behavior

The Mission Planner adjusts KS0 visibility and WKEK label based on the selected equipment profile:

| Equipment Profile | KS0 Visibility | WKEK Label | Reason |
|-------------------|----------------|------------|--------|
| **L3Harris** | Hidden | WKEK / WBKEK: | KS0 not supported for L3Harris radios |
| **Collins/Raytheon** | Visible | WKEK / WBKEK: | KS0 (Key Set Zero) available for Collins radios |
| **AN/PRC-161** | Hidden | KEK: | KS0 not supported for AN/PRC-161 radios; uses simplified KEK label |

**Implementation Details:**
- When user selects L3Harris: KS0 controls (Short Title and Edition) are hidden; WKEK label is "WKEK / WBKEK:"
- When user selects Collins/Raytheon: KS0 controls are shown; WKEK label is "WKEK / WBKEK:"
- When user selects AN/PRC-161: KS0 controls are hidden (same behavior as L3Harris); WKEK label changes to "KEK:"
- Visibility and label updates automatically when equipment profile changes
- When adding new mission groups, KS0 visibility and WKEK label match current equipment profile
- When duplicating mission groups, KS0 visibility and WKEK label match current equipment profile
- KS0 change handlers respect visibility - no auto-population when KS0 is hidden

## Technical Implementation

### Architecture
- Follows MVVM pattern with `MissionPlanViewModel` as parent
- Each mission group represented by `MissionGroupViewModel`
- `MissionPlanPage` (WPF view) binds to `MissionPlanViewModel`

### Data Sources
- **Short Titles**: Loaded from database, filtered by KeyType
  - BTEK: KeyType = 6 (TEK)
  - WKEK: KeyType = 2 (KEK)
  - KS0: KeyType = 2 (KEK)
- **Editions**: Loaded from database via `RetrieveWKEKEditionsFromDatabase()`
  - Includes `.Include(e => e.ShortTitle)` to ensure navigation property is loaded
  - Filtered by matching ShortTitleId

### Key Methods

#### `AutoPopulateWKEKFromBTEK(CoreModels.ShortTitle btekShortTitle)`
Primary auto-linking logic:
1. Searches for candidate WKEKs containing "KL" in NationalShortTitle
2. Tests pattern matching: swap "KL" → "BL" and compare to BTEK name
3. When match found: queries database for WKEK editions with matching ShortTitleId
4. Selects WKEK edition that matches BTEK edition name
5. Sets all MVVM properties: WKEKShortTitle, WKEKEditions, WKEKEdition

#### `OnBTEKEditionChanged`
Event handler for BTEK edition changes:
- Calls date calculation functions
- Validates dates across all selected keys
- Calculates BTEK segment count
- **Auto-updates WKEK edition** to match new BTEK edition name

#### `OnWKEKShortTitleChanged`
Event handler for WKEK short title changes:
- Skips during auto-population (controlled by `_isAutoPopulatingWKEK` flag)
- **Queries database directly** via `RetrieveWKEKEditionsFromDatabase()` to load WKEK editions
- Filters editions by matching ShortTitle.NationalShortTitle
- Selects first edition automatically
- Logs the number of editions loaded for debugging

#### `OnKS0ShortTitleChanged`
Event handler for KS0 short title changes:
- **Queries database directly** via `RetrieveWKEKEditionsFromDatabase()` to load KS0 editions (also KeyType=2)
- Filters editions by matching ShortTitle.NationalShortTitle
- Selects first edition automatically
- Logs the number of editions loaded for debugging

#### `OnStartDateChanged`
Event handler for start date changes:
- Automatically calculates and updates the end date to the last day of the selected start month
- Ensures end date is always consistent with the selected start date

#### `OnWIIValueChanged`
Event handler for WII value changes:
- Validates that WII is exactly 9 characters
- Sets WIIValidationWarning and HasWIIValidationError accordingly
- Logs warning for invalid WII entries

### Database Queries

#### RetrieveWKEKEditionsFromDatabase()
```csharp
db.Editions
    .Include(e => e.ShortTitle)
    .Include(e => e.Segment)
    .Where(e => e.Segment != null && e.Segment.Any(s => s.KeyType == 2))
    .Select(e => new CoreModels.Edition { ... })
    .ToList();
```
- Loads all WKEK editions (KeyType=2)
- Includes ShortTitle navigation property for name matching
- Includes Segment for KeyType filtering

## Use Cases

### Use Case 1: Basic Mission Planning with Auto-Linking
1. User clicks "Add Mission Group"
2. User selects BTEK "USEAD BL123456 880091"
3. **System auto-selects** WKEK "USEAD KL123456 880091"
4. **System loads** all available WKEK editions
5. **System auto-selects** matching edition (e.g., "Jan 2026")
6. User configures other parameters (CVLL, encryption, dates)
7. User saves mission plan

### Use Case 2: Changing Edition
1. User has linked BTEK and WKEK (both on "Jan 2026" edition)
2. User changes BTEK edition to "Feb 2026"
3. **System auto-updates** WKEK edition to "Feb 2026"
4. Dates auto-recalculate based on new edition

### Use Case 2b: KS0 Selection
1. User selects KS0 short title (optional parameter)
2. **System loads** all available editions for the selected KS0 from database (KeyType=2)
3. **System auto-selects** the first available edition
4. Dates recalculate to include the KS0 edition's effective date
5. System validates that BTEK, WKEK, and KS0 dates are all in the same month (warns if not)

### Use Case 2c: Equipment Profile Change Impacting KS0 Visibility
1. User has Collins/Raytheon selected with KS0 controls visible and configured
2. User selects L3Harris as equipment profile
3. **System hides** KS0 controls (Short Title and Edition dropdowns) - no longer applicable
4. KS0 values remain stored but are UI-hidden, preserving user data
5. User later selects Collins/Raytheon again: KS0 controls reappear with previous values

### Use Case 3: Manual WKEK Override
1. User selects BTEK with "BL" variant
2. System auto-links and auto-selects WKEK
3. User manually changes WKEK selection to different short title
4. WKEK editions reload for new selection
5. Future BTEK edition changes do **NOT** affect this manually-chosen WKEK

### Use Case 4: Adding Multiple Groups
1. User adds first mission group, configures with auto-linking
2. User clicks "Duplicate Group" button
3. New group复制s all settings from first group
4. User modifies specific parameters as needed
5. User reorders groups using up/down arrows

## Validation Rules

### Date Validation
- If BTEK, WKEK, and KS0 editions are from different months, display warning:
  ```
  Warning: BTEK, WBKEK/WKEK, and KS0 dates are in different months.
  Please ensure all keys are for the same operational period.
  ```

### WII Validation
- WII (Waveform Instance Identifier) must be exactly 9 characters in length
- UI enforces MaxLength=9 on the WII field (user cannot exceed 9 characters)
- Validation occurs in real-time as user types in the WII field
- Red warning message displays if WII length != 9:
  ```
  WII (Waveform Instance Identifier) must be exactly 9 characters. Current length: {X}.
  ```

### Segment Count Validation
- BTEK segment count must not exceed 31 (MIDS specification limit)
- Calculated based on edition's month and segment start day
- Example: If edition is Feb 2025 (28 days) and start day is 5, segment count = 24

### Empty Field Validation
- Mission group requires BTEK short title and edition
- WKEK short title and edition are optional if no auto-linked WKEK exists
- KS0 fields are optional

## EKMS 308 FDU Header Option

### Overview
The Mission Planner supports an optional EKMS 308 FDU (File Data Unit) header prepend feature for all exported mission group files (BTEK, WKEK/KEK/WBKEK, and KS0).

### FDU Header Structure
When enabled, the following 4-byte header is prepended to each exported binary file:

| Byte Position | Content | Description |
|---------------|---------|-------------|
| 0 | FCI High | FCI byte high nibble (0x01 for Fill, 0x02 for Issue) |
| 1 | FCI Low | FCI byte low nibble (0xB0) |
| 2 | Length MSB | Data length high byte (big-endian) |
| 3 | Length LSB | Data length low byte (big-endian) |
| 4+ | Data | MIDS JTRS tag (103 bytes) + Encrypted key (variable) |

### FDU Variants
| Variant | FCI Value | Description |
|---------|-----------|-------------|
| Fill | 0x01B0 | Transfer key/data to end user (immediate) |
| Issue | 0x02B0 | Transfer key for later forwarding |

### UI Controls
Located below the "Export to CD" button in the Mission Planner page:
- **Checkbox**: "Prepend EKMS 308 FDU Header" - Enables/disables the feature (default: unchecked/disabled)
- **Radio Button**: "Fill (0x01B0)" - Default FDU variant
- **Radio Button**: "Issue (0x02B0)" - Alternative FDU variant

### Export Format Examples

**Without FDU Header (default):**
```
[MIDS JTRS Tag: 103 bytes][Encrypted Key: variable]
Total: 103 + EncryptedKey.Length bytes
```

**With FDU Header (Fill variant):**
```
[0x01][0xB0][Length MSB][Length LSB][MIDS JTRS Tag: 103 bytes][Encrypted Key: variable]
Total: 4 + 103 + EncryptedKey.Length bytes
```

**With FDU Header (Issue variant):**
```
[0x02][0xB0][Length MSB][Length LSB][MIDS JTRS Tag: 103 bytes][Encrypted Key: variable]
Total: 4 + 103 + EncryptedKey.Length bytes
```

### Implementation Details
- The FDU header is applied to all export formats: L3Harris, Collins/Raytheon, and AN/PRC-161
- The length field is calculated as: `MIDSJTRS.Length + EncryptKey.Length`
- Length is encoded in big-endian format (MSB first) as per EKMS 308 specification
- The feature is disabled by default to maintain backward compatibility

## Default Values

When creating a new Mission Group, the following default values are applied:

| Field | Default Value | Notes |
|-------|---------------|-------|
| **Mission CVLL** | R001 | First item in CVLL dropdown (R001-R127) |
| **Encryption Type** | AES | First item in encryption dropdown |
| **Start Date** | 1st of current month (first group) / month following previous group's end date (subsequent groups) | Formatted as MM/dd/yyyy |
| **End Date** | Last day of start month | Auto-calculated from start date |

## WII Persistence

The Mission Planner remembers the last used WII (Waveform Instance Identifier) across application sessions:

- When a user selects a valid WII (exactly 9 characters), it is saved to application settings
- On subsequent application launches, the last used WII is automatically selected when creating new Mission Groups
- WII values are stored in `settings.json` under the `LastUsedWII` property
- Only valid WIIs (exactly 9 characters) are persisted
- WIIs are user-defined - no default WIIs are provided by the application

## State Flags

### `_isAutoPopulatingWKEK`
- `true` during BTEK auto-linking process
- Prevents `OnWKEKShortTitleChanged` from overwriting values during auto-population
- Must be reset to `false` before returning from `AutoPopulateWKEKFromBTEK`

## Logging

Key logging points:
- Auto-population triggered: `AutoPopulateWKEKFromBTEK called: BTEK=..., Base=..., Found N WKEK candidates`
- WKEK match found: `Found matching WKEK: ...`
- Editions loaded: `Matching editions found: N`
- WKEK edition updated: `Auto-updated WKEK edition to match BTEK edition: ...`
- Date mismatch warning: `Date mismatch detected for group N`
- No matching WKEK: `No matching WKEK found for BTEK: ...`

## Dependencies

### External Dependencies
- **Entity Framework Core 8.0.8**: Database access and ORM
- **Newtonsoft.Json 13.0.3**: JSON serialization for SDA export
- **log4net 3.0.1**: Logging framework
- **MahApps.Metro 2.4.10**: Modern WPF UI framework
- **CommunityToolkit.Mvvm 8.3.2**: MVVM pattern helpers

### Internal Services
- `SerializeService.RetrieveShortTitlesFromDatabase()`: Load short titles
- `SerializeService.RetrieveEditionsFromDatabase()`: Load BTEK editions (KeyType=6)
- `SerializeService.RetrieveWKEKEditionsFromDatabase()`: Load WKEK editions (KeyType=2)
- `SerializeService.RetrieveMissionsFromDatabase()`: Load saved mission plans

## Known Limitations

1. **Auto-Linking is One-Way**: Only BTEK → WKEK auto-linking is supported. Changing WKEK manual does not update BTEK.
2. **Edition Name Matching Only**: Editions are matched by string comparison of edition names. If names don't exactly match despite being the same period, manual selection is required.
3. **Segment Navigation Property**: The `Edition.Segment` EF Core navigation property must be loaded for KeyType filtering to work correctly.

## Future Enhancements

1. **Bidirectional Auto-Linking**: Support WKEK → BTEK auto-linking for reverse workflow
2. **Smart Edition Matching**: Use date ranges instead of name strings for more robust edition matching
3. **Batch Configuration**: Apply same configuration across multiple mission groups
4. **Import/Export Mission Plans**: Save and load complete mission configurations
5. **Visual Timeline**: Display key validity periods on a visual timeline
6. **Conflict Detection**: Warn when groups have overlapping key periods in different configurations

## Export File Format

### BTEK/WKEK/KS0 Export Structure

When exporting mission plans to CD, the system creates binary files with the following structure:

**File Format:**
```
┌─────────────────────────────┐
│  MIDS JTRS Tag (103 bytes)  │
├─────────────────────────────┤
│  Encrypted Key Data (N)     │
└─────────────────────────────┘
```

**Total File Size:** 103 bytes (MIDS JTRS tag) + EncryptedKey.Length bytes

**Directory Structure:**
```
<ExportRoot>/
├── BTEK/
│   └── <WII>/<CVLL>/<BTEKShortTitle>/<Edition>/
│       └── seg_<N>.bin
├── WKEK/
│   └── <WKEKShortTitle>/<Edition>/
│       └── seg_01.bin
└── KS0/
    └── <KS0ShortTitle>/<Edition>/
        └── seg_01.bin
```

**Export Process:**
1. **BTEK Export**: For each segment in the BTEK edition (based on Segment Start Day and Segment Count):
   - Generate MIDS JTRS tag using the AN/PRC-161 BTEK template
   - Write tag (103 bytes) + encrypted key data to `seg_<N>.bin`

2. **WKEK Export**: For the selected WKEK edition:
   - Generate MIDS JTRS tag using the AN/PRC-161 EKEK template
   - Write tag (103 bytes) + encrypted key data to `seg_01.bin`

3. **KS0 Export**: For the selected KS0 edition:
   - Generate MIDS JTRS tag (KS0 key function)
   - Write tag (103 bytes) + encrypted key data to `seg_01.bin`

**Key Retrieval:**
- Segments are retrieved using `SerializeService.RetrieveSelectSegmentsFromDatabase(EditionId)`
- The `EncryptedKey` field is Base64 decoded before writing to the output file
- Each segment produces one binary file with its corresponding MIDS JTRS tag

## References

- **MDS-JTRS Specification**: https://[internal-link]
- **EKMS 308 Specification (DS-100-1)**: Data tagging and key material formats
- **SDA Export Module**: Separate module for exporting mission plans to Spectral Domain Analyzer
- **SerializeService**: `ReceivedKeyProcessorApp/Services/SerializeService.cs` - Segment retrieval and database operations