#include "HyperTwistTraining/HyperTwistTrainingCaptureHistoryLibrary.h"

namespace HyperTwistTrainingCaptureHistoryLibraryInternal
{
	const TCHAR* CaptureHistoryRepo = TEXT("screenpipe/screenpipe");
	const TCHAR* CaptureHistoryLicense = TEXT("MIT OR Apache-2.0 core; enterprise license inside ee/");

	FHyperTwistTrainingSourceAttribution MakeAttribution(
		const FString& TrackId,
		const FString& Notes
	)
	{
		FHyperTwistTrainingSourceAttribution Attribution;
		Attribution.SourceMode = EHyperTwistTrainingSourceMode::DirectDonor;
		Attribution.SourceRepo = CaptureHistoryRepo;
		Attribution.SourceLicense = CaptureHistoryLicense;
		Attribution.SourceTrackId = TrackId;
		Attribution.SourceNotes = Notes;
		return Attribution;
	}

	FHyperTwistTrainingCaptureHistoryPackageReference MakePackageReference(
		const FString& PackageId,
		const FString& Label,
		const FString& PackagePath,
		const FString& UsagePosture,
		const FString& LicensePosture,
		const FString& Summary,
		const TArray<FString>& ApprovedWorkflowTags,
		const TArray<FString>& ExplicitExclusions,
		const FHyperTwistTrainingSourceAttribution& SourceAttribution
	)
	{
		FHyperTwistTrainingCaptureHistoryPackageReference Reference;
		Reference.PackageId = PackageId;
		Reference.Label = Label;
		Reference.PackagePath = PackagePath;
		Reference.UsagePosture = UsagePosture;
		Reference.LicensePosture = LicensePosture;
		Reference.Summary = Summary;
		Reference.ApprovedWorkflowTags = ApprovedWorkflowTags;
		Reference.ExplicitExclusions = ExplicitExclusions;
		Reference.SourceAttribution = SourceAttribution;
		return Reference;
	}
}

FHyperTwistTrainingCaptureHistoryReferenceBundle
UHyperTwistTrainingCaptureHistoryLibrary::BuildBundledCaptureHistoryReferenceBundle()
{
	using namespace HyperTwistTrainingCaptureHistoryLibraryInternal;

	FHyperTwistTrainingCaptureHistoryReferenceBundle Bundle;
	Bundle.ReferenceUtc = TEXT("2026-05-13T23:59:00Z");
	Bundle.PrimaryEventCaptureContractId = TEXT("screenpipe-event-driven-capture-and-triggering");
	Bundle.PrimaryPipePermissionContractId = TEXT("screenpipe-pipe-permission-and-backpressure");
	Bundle.PrimaryPersistenceContractId = TEXT("screenpipe-write-queue-and-retention");
	Bundle.PrimaryVaultLifecycleContractId = TEXT("screenpipe-vault-lock-unlock-and-migration");
	Bundle.PrimaryTimelineReviewContractId = TEXT("screenpipe-rewind-timeline-review");
	Bundle.PrimaryComplianceBoundaryId = TEXT("screenpipe-core-capture-history-and-ee-exclusion-boundary");

	Bundle.PackageReferences =
	{
		MakePackageReference(
			TEXT("package/screenpipe-root"),
			TEXT("screenpipe root core"),
			TEXT("./"),
			TEXT("bounded-capture-history-reference"),
			TEXT("MIT OR Apache-2.0 core; enterprise-restricted ee/ subtree excluded"),
			TEXT("Root monorepo boundary reference for local capture, history, replay, permissions, vault, and timeline extraction while keeping the broader AI-memory shell and enterprise subtree outside HyperTwist ownership."),
			{TEXT("capture-history-boundary"), TEXT("source-routing"), TEXT("notice-retention")},
			{
				TEXT("ee/ subtree"),
				TEXT("whole AI-memory or assistant product shell adoption"),
				TEXT("broad local-agent platform ownership")
			},
			MakeAttribution(
				TEXT("capture-history/package-root"),
				TEXT("Preserves the root permissive-core versus ee/ split so HyperTwist can land a bounded local capture and replay lane without inheriting the larger product shell.")
			)
		),
		MakePackageReference(
			TEXT("package/screenpipe-engine-capture"),
			TEXT("Event-driven capture engine surfaces"),
			TEXT("./crates/screenpipe-engine/src/lib.rs + ./crates/screenpipe-engine/src/event_driven_capture.rs"),
			TEXT("bounded-event-capture-reference"),
			TEXT("MIT OR Apache-2.0 core"),
			TEXT("Event-driven capture triggers, debounce posture, visual-change heuristics, OCR-and-screenshot capture pairing, and recording-lifecycle seams for first-party HyperTwist capture support."),
			{TEXT("event-capture"), TEXT("trigger-routing"), TEXT("visual-change-detection")},
			{
				TEXT("whole recording product shell"),
				TEXT("generic desktop surveillance framing")
			},
			MakeAttribution(
				TEXT("capture-history/event-capture"),
				TEXT("Preserves event-triggered capture, debounce, screenshot/OCR pairing, and recording-lifecycle seams from the retained screenpipe engine lane.")
			)
		),
		MakePackageReference(
			TEXT("package/screenpipe-engine-permissions"),
			TEXT("Pipe permission middleware surfaces"),
			TEXT("./crates/screenpipe-engine/src/pipe_permissions_middleware.rs"),
			TEXT("bounded-permission-reference"),
			TEXT("MIT OR Apache-2.0 core"),
			TEXT("Deterministic pipe permission, token gating, content-type allowlisting, timeout, and concurrency-limit reference surfaces for first-party HyperTwist capture and replay sidecars."),
			{TEXT("pipe-permissions"), TEXT("endpoint-gating"), TEXT("backpressure")},
			{
				TEXT("whole pipe or agent platform ownership"),
				TEXT("enterprise routing or monetization surfaces")
			},
			MakeAttribution(
				TEXT("capture-history/pipe-permissions"),
				TEXT("Preserves the deterministic permission, backpressure, and endpoint-routing seams from the retained screenpipe pipe middleware lane.")
			)
		),
		MakePackageReference(
			TEXT("package/screenpipe-db-write-queue"),
			TEXT("Capture database and write-queue surfaces"),
			TEXT("./crates/screenpipe-db/src/lib.rs + ./crates/screenpipe-db/src/write_queue.rs"),
			TEXT("bounded-persistence-reference"),
			TEXT("MIT OR Apache-2.0 core"),
			TEXT("Write coalescing, batch transaction, single-writer queue, sleep-aware pause/resume, and retention-aware local persistence reference surfaces for first-party HyperTwist replay support."),
			{TEXT("capture-persistence"), TEXT("write-queue"), TEXT("retention")},
			{
				TEXT("generic database platform ownership"),
				TEXT("whole multi-tenant data stack adoption")
			},
			MakeAttribution(
				TEXT("capture-history/persistence"),
				TEXT("Preserves the local write-queue, batching, retention, and sleep-aware persistence seams from the retained screenpipe database lane.")
			)
		),
		MakePackageReference(
			TEXT("package/screenpipe-vault"),
			TEXT("Vault lifecycle surfaces"),
			TEXT("./crates/screenpipe-vault/src/lib.rs + ./crates/screenpipe-vault/src/manager.rs"),
			TEXT("bounded-vault-reference"),
			TEXT("MIT OR Apache-2.0 core"),
			TEXT("Vault lock, unlock, encryption, migration, key lifecycle, and recording-precondition reference surfaces for first-party HyperTwist private capture-history handling."),
			{TEXT("vault-lifecycle"), TEXT("encryption-state"), TEXT("migration-safety")},
			{
				TEXT("whole secrets platform ownership"),
				TEXT("enterprise sync or team-vault product shell")
			},
			MakeAttribution(
				TEXT("capture-history/vault"),
				TEXT("Preserves the lock/unlock, migration, and recording-safety seams from the retained screenpipe vault lane.")
			)
		),
		MakePackageReference(
			TEXT("package/screenpipe-rewind-timeline"),
			TEXT("Rewind timeline review surfaces"),
			TEXT("./apps/screenpipe-app-tauri/components/rewind/timeline/timeline.tsx"),
			TEXT("bounded-timeline-review-reference"),
			TEXT("MIT OR Apache-2.0 core"),
			TEXT("Timeline grouping, filtering, replay controls, review context, and operator-facing rewind inspection surfaces for first-party HyperTwist capture-history review workflows."),
			{TEXT("timeline-review"), TEXT("replay-inspection"), TEXT("filtering")},
			{
				TEXT("whole Tauri app shell"),
				TEXT("general AI memory chat or inbox surfaces")
			},
			MakeAttribution(
				TEXT("capture-history/timeline-review"),
				TEXT("Preserves the rewind grouping, filtering, and playback review seams from the retained screenpipe timeline lane without inheriting the surrounding app shell.")
			)
		)
	};

	FHyperTwistTrainingEventCaptureContract EventCapture;
	EventCapture.ContractId = TEXT("screenpipe-event-driven-capture-and-triggering");
	EventCapture.Title = TEXT("Event-driven capture and triggering");
	EventCapture.Summary = TEXT("First-party HyperTwist event-capture contract preserving the retained screenpipe trigger model, screenshot-plus-context capture pairing, debounce posture, and visual-change fallback behavior for bounded local replay support.");
	EventCapture.TriggerKinds =
	{
		TEXT("app-switch"),
		TEXT("window-focus"),
		TEXT("mouse-click"),
		TEXT("typing-pause"),
		TEXT("scroll-stop"),
		TEXT("clipboard-change"),
		TEXT("visual-change"),
		TEXT("idle-fallback"),
		TEXT("manual-capture")
	};
	EventCapture.CaptureModalities =
	{
		TEXT("paired screenshot plus accessibility capture"),
		TEXT("OCR fallback when richer semantic context is unavailable"),
		TEXT("hot-frame cache and delayed frame flush for replay slices"),
		TEXT("window-aware metadata capture for later grouping and review")
	};
	EventCapture.DebounceRules =
	{
		TEXT("preserve debounce windows per event family rather than treating every trigger as an immediate capture"),
		TEXT("typing pause and scroll stop triggers should wait for inactivity thresholds before capture"),
		TEXT("suppress noisy duplicate captures when the active surface has not materially changed")
	};
	EventCapture.IdleAndVisualRules =
	{
		TEXT("preserve idle fallback when no higher-value trigger fires within the configured interval"),
		TEXT("treat visual-change capture as a bounded fallback rather than the primary recording mode"),
		TEXT("preserve configurable visual-diff threshold semantics for screenshot-triggered refresh")
	};
	EventCapture.RecordingLifecycleRules =
	{
		TEXT("preserve start, running, paused, and stopped lifecycle distinctions"),
		TEXT("capture should pause cleanly during system sleep or explicit suspension"),
		TEXT("resume should re-establish triggers without duplicating stale buffered slices")
	};
	EventCapture.ApprovedWorkflowTags =
	{
		TEXT("event-capture"),
		TEXT("trigger-routing"),
		TEXT("replay-support"),
		TEXT("visual-change-detection")
	};
	EventCapture.ExplicitExclusions =
	{
		TEXT("whole memory product shell"),
		TEXT("broad desktop surveillance framing"),
		TEXT("ee/ enterprise capture surfaces")
	};
	EventCapture.SourceAttribution = MakeAttribution(
		TEXT("capture-history/event-capture-contract"),
		TEXT("Preserves the event-driven capture, debounce, and visual-change seams from the retained screenpipe engine lane for first-party HyperTwist capture support.")
	);
	Bundle.EventCaptureContracts = {EventCapture};

	FHyperTwistTrainingPipePermissionContract Permission;
	Permission.ContractId = TEXT("screenpipe-pipe-permission-and-backpressure");
	Permission.Title = TEXT("Pipe permission and backpressure");
	Permission.Summary = TEXT("First-party HyperTwist permission contract preserving deterministic endpoint gating, pipe token posture, content-type filtering, timeout handling, and concurrency limits from the retained screenpipe middleware lane.");
	Permission.TokenRules =
	{
		TEXT("preserve explicit bearer-token posture for local pipe access instead of ambient trust"),
		TEXT("differentiate deny, allow, and default-allowlist outcomes rather than collapsing to a single boolean"),
		TEXT("treat endpoint authorization as a routing concern before side effects begin")
	};
	Permission.ContentFilterRules =
	{
		TEXT("preserve content-type gates for high-risk audio and media endpoints"),
		TEXT("allowlist endpoint families explicitly instead of falling back to open generic execution"),
		TEXT("surface permission failures as deterministic operator-readable responses")
	};
	Permission.BackpressureRules =
	{
		TEXT("preserve semaphore-limited concurrent pipe work"),
		TEXT("fast-fail when backpressure thresholds are exceeded"),
		TEXT("treat timeout and cancellation as explicit outcomes rather than silent retries")
	};
	Permission.EndpointRoutingRules =
	{
		TEXT("preserve route-to-handler separation from authorization logic"),
		TEXT("attach audit-friendly reason codes to denied or downgraded requests"),
		TEXT("keep local capture-history sidecar endpoints separate from generic product shell routing")
	};
	Permission.ApprovedWorkflowTags =
	{
		TEXT("pipe-permissions"),
		TEXT("endpoint-gating"),
		TEXT("backpressure"),
		TEXT("local-sidecar")
	};
	Permission.ExplicitExclusions =
	{
		TEXT("whole pipe marketplace or agent platform ownership"),
		TEXT("enterprise billing or seat-management surfaces"),
		TEXT("ee/ enterprise middleware")
	};
	Permission.SourceAttribution = MakeAttribution(
		TEXT("capture-history/pipe-permission-contract"),
		TEXT("Preserves deterministic permission, allowlist, and backpressure semantics from the retained screenpipe middleware lane for first-party HyperTwist sidecar access.")
	);
	Bundle.PipePermissionContracts = {Permission};

	FHyperTwistTrainingCapturePersistenceContract Persistence;
	Persistence.ContractId = TEXT("screenpipe-write-queue-and-retention");
	Persistence.Title = TEXT("Write queue and retention");
	Persistence.Summary = TEXT("First-party HyperTwist capture-persistence contract preserving the retained screenpipe write-queue, batch transaction, retention, and sleep-aware pause/resume seams for local replay support.");
	Persistence.QueueSemantics =
	{
		TEXT("preserve single-writer queue posture for capture-event materialization"),
		TEXT("coalesce related writes before committing them as replay slices"),
		TEXT("serialize sync-sensitive tables and dependent writes deterministically")
	};
	Persistence.BatchRules =
	{
		TEXT("preserve batched transaction boundaries for capture, OCR, and metadata updates"),
		TEXT("flush in bounded batches rather than per-event row churn"),
		TEXT("prefer durable local consistency over optimistic unordered fanout")
	};
	Persistence.SleepWakeRules =
	{
		TEXT("pause write activity during system sleep"),
		TEXT("resume from wake with queue integrity preserved"),
		TEXT("do not re-emit stale buffered work after a clean pause")
	};
	Persistence.RetentionRules =
	{
		TEXT("treat retention and pruning as first-class local lifecycle concerns"),
		TEXT("separate capture ingestion from historical cleanup operations"),
		TEXT("preserve deterministic replay-history ordering through cleanup passes")
	};
	Persistence.ApprovedWorkflowTags =
	{
		TEXT("capture-persistence"),
		TEXT("write-queue"),
		TEXT("retention"),
		TEXT("replay-support")
	};
	Persistence.ExplicitExclusions =
	{
		TEXT("generic database platform ownership"),
		TEXT("distributed sync pipeline ownership"),
		TEXT("ee/ enterprise persistence surfaces")
	};
	Persistence.SourceAttribution = MakeAttribution(
		TEXT("capture-history/persistence-contract"),
		TEXT("Preserves write coalescing, batching, sleep-aware pause/resume, and retention semantics from the retained screenpipe database lane for first-party HyperTwist replay history support.")
	);
	Bundle.PersistenceContracts = {Persistence};

	FHyperTwistTrainingVaultLifecycleContract Vault;
	Vault.ContractId = TEXT("screenpipe-vault-lock-unlock-and-migration");
	Vault.Title = TEXT("Vault lock, unlock, and migration");
	Vault.Summary = TEXT("First-party HyperTwist vault lifecycle contract preserving lock, unlock, migration, encryption-state, and recording-precondition seams from the retained screenpipe vault lane.");
	Vault.LifecycleStates =
	{
		TEXT("none"),
		TEXT("locked"),
		TEXT("unlocked"),
		TEXT("migrating")
	};
	Vault.LockUnlockRules =
	{
		TEXT("lock should encrypt local vault data and clear active plaintext access"),
		TEXT("unlock should decrypt and restore access only after key validation succeeds"),
		TEXT("vault state transitions should be explicit and operator-visible")
	};
	Vault.MigrationRules =
	{
		TEXT("preserve migration sentinel and progress posture"),
		TEXT("treat migrations as crash-sensitive operations that require resumable or retry-safe state"),
		TEXT("complete migration before normal replay or capture access resumes")
	};
	Vault.RecordingPreconditions =
	{
		TEXT("recording should stop before vault lock or migration begins"),
		TEXT("database handles should close cleanly before encryption-state transitions"),
		TEXT("capture-history sidecars should refuse unsafe writes when the vault is not in an unlocked ready state")
	};
	Vault.ApprovedWorkflowTags =
	{
		TEXT("vault-lifecycle"),
		TEXT("encryption-state"),
		TEXT("migration-safety"),
		TEXT("recording-preconditions")
	};
	Vault.ExplicitExclusions =
	{
		TEXT("whole enterprise sync shell"),
		TEXT("team credential platform ownership"),
		TEXT("ee/ enterprise vault extensions")
	};
	Vault.SourceAttribution = MakeAttribution(
		TEXT("capture-history/vault-contract"),
		TEXT("Preserves lock, unlock, migration, and recording-safety seams from the retained screenpipe vault lane for first-party HyperTwist private capture-history handling.")
	);
	Bundle.VaultLifecycleContracts = {Vault};

	FHyperTwistTrainingTimelineReviewContract Timeline;
	Timeline.ContractId = TEXT("screenpipe-rewind-timeline-review");
	Timeline.Title = TEXT("Rewind timeline review");
	Timeline.Summary = TEXT("First-party HyperTwist timeline-review contract preserving the retained screenpipe rewind grouping, filtering, replay-control, and review-context seams for local capture-history inspection.");
	Timeline.GroupingAxes =
	{
		TEXT("app"),
		TEXT("domain"),
		TEXT("speaker"),
		TEXT("meeting"),
		TEXT("day-boundary"),
		TEXT("device")
	};
	Timeline.FilterFacets =
	{
		TEXT("device"),
		TEXT("app"),
		TEXT("domain"),
		TEXT("speaker"),
		TEXT("tag"),
		TEXT("meeting")
	};
	Timeline.ReplayControls =
	{
		TEXT("zoom"),
		TEXT("selection"),
		TEXT("refresh"),
		TEXT("play-pause"),
		TEXT("scrub-to-range")
	};
	Timeline.ContextSurfaces =
	{
		TEXT("app context"),
		TEXT("tag toolbar"),
		TEXT("speaker context"),
		TEXT("AI or pipe hook points"),
		TEXT("rewind slice metadata")
	};
	Timeline.ApprovedWorkflowTags =
	{
		TEXT("timeline-review"),
		TEXT("replay-inspection"),
		TEXT("grouping"),
		TEXT("filtering")
	};
	Timeline.ExplicitExclusions =
	{
		TEXT("whole Tauri app shell"),
		TEXT("chat or inbox ownership"),
		TEXT("ee/ enterprise timeline overlays")
	};
	Timeline.SourceAttribution = MakeAttribution(
		TEXT("capture-history/timeline-contract"),
		TEXT("Preserves rewind grouping, filtering, and replay-control seams from the retained screenpipe timeline lane for first-party HyperTwist review workflows.")
	);
	Bundle.TimelineReviewContracts = {Timeline};

	FHyperTwistTrainingCaptureHistoryComplianceBoundary ComplianceBoundary;
	ComplianceBoundary.BoundaryId = TEXT("screenpipe-core-capture-history-and-ee-exclusion-boundary");
	ComplianceBoundary.Title = TEXT("screenpipe core capture-history and ee exclusion boundary");
	ComplianceBoundary.Summary = TEXT("First-party HyperTwist compliance boundary for using screenpipe permissive core capture, history, replay, pipe-permission, and vault patterns while keeping the enterprise-restricted ee subtree and the broader AI-memory product shell outside the landed lane.");
	ComplianceBoundary.AllowedSourceRoots =
	{
		TEXT("./crates/screenpipe-engine"),
		TEXT("./crates/screenpipe-db"),
		TEXT("./crates/screenpipe-vault"),
		TEXT("./apps/screenpipe-app-tauri/components/rewind/timeline")
	};
	ComplianceBoundary.ExcludedSourceRoots =
	{
		TEXT("./ee"),
		TEXT("./apps/screenpipe-app-tauri/app"),
		TEXT("./apps/screenpipe-app-tauri/src-tauri"),
		TEXT("./packages/agent"),
		TEXT("./packages/ai-gateway"),
		TEXT("./packages/sync")
	};
	ComplianceBoundary.RequiredNoticeActions =
	{
		TEXT("preserve root MIT-or-Apache core license materials for any reused or closely adapted core-path code"),
		TEXT("keep the ee/ exclusion explicit in packet docs, manifests, and future widening notes"),
		TEXT("do not represent the landed lane as permission to consume the broader screenpipe product shell")
	};
	ComplianceBoundary.ProvenanceCaveats =
	{
		TEXT("the retained value is local capture, replay history, deterministic permissions, vault lifecycle, and rewind review rather than a general AI-memory product"),
		TEXT("the timeline lane is retained only as a bounded review surface beneath first-party HyperTwist runtime ownership"),
		TEXT("HyperTwist should preserve these seams in first-party contracts instead of inheriting the surrounding shell, packages, or enterprise posture")
	};
	ComplianceBoundary.ExplicitExclusions =
	{
		TEXT("ee/ subtree use without separate rights"),
		TEXT("whole AI-memory product shell adoption"),
		TEXT("generic browser-agent platform ownership"),
		TEXT("enterprise sync and cloud service inheritance")
	};
	ComplianceBoundary.SourceAttribution = MakeAttribution(
		TEXT("capture-history/compliance-boundary"),
		TEXT("Preserves the screenpipe permissive-core versus ee/ boundary and the bounded capture-history donor posture for first-party HyperTwist implementation.")
	);
	Bundle.ComplianceBoundaries = {ComplianceBoundary};

	return Bundle;
}

bool UHyperTwistTrainingCaptureHistoryLibrary::TryGetPackageReferenceById(
	const FHyperTwistTrainingCaptureHistoryReferenceBundle& Bundle,
	const FString& PackageId,
	FHyperTwistTrainingCaptureHistoryPackageReference& OutReference
)
{
	for (const FHyperTwistTrainingCaptureHistoryPackageReference& Reference : Bundle.PackageReferences)
	{
		if (Reference.PackageId.Equals(PackageId, ESearchCase::IgnoreCase))
		{
			OutReference = Reference;
			return true;
		}
	}

	OutReference = FHyperTwistTrainingCaptureHistoryPackageReference();
	return false;
}

bool UHyperTwistTrainingCaptureHistoryLibrary::TryGetEventCaptureContractById(
	const FHyperTwistTrainingCaptureHistoryReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingEventCaptureContract& OutContract
)
{
	for (const FHyperTwistTrainingEventCaptureContract& Contract : Bundle.EventCaptureContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingEventCaptureContract();
	return false;
}

bool UHyperTwistTrainingCaptureHistoryLibrary::TryGetPipePermissionContractById(
	const FHyperTwistTrainingCaptureHistoryReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingPipePermissionContract& OutContract
)
{
	for (const FHyperTwistTrainingPipePermissionContract& Contract : Bundle.PipePermissionContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingPipePermissionContract();
	return false;
}

bool UHyperTwistTrainingCaptureHistoryLibrary::TryGetPersistenceContractById(
	const FHyperTwistTrainingCaptureHistoryReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingCapturePersistenceContract& OutContract
)
{
	for (const FHyperTwistTrainingCapturePersistenceContract& Contract : Bundle.PersistenceContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingCapturePersistenceContract();
	return false;
}

bool UHyperTwistTrainingCaptureHistoryLibrary::TryGetVaultLifecycleContractById(
	const FHyperTwistTrainingCaptureHistoryReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingVaultLifecycleContract& OutContract
)
{
	for (const FHyperTwistTrainingVaultLifecycleContract& Contract : Bundle.VaultLifecycleContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingVaultLifecycleContract();
	return false;
}

bool UHyperTwistTrainingCaptureHistoryLibrary::TryGetTimelineReviewContractById(
	const FHyperTwistTrainingCaptureHistoryReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingTimelineReviewContract& OutContract
)
{
	for (const FHyperTwistTrainingTimelineReviewContract& Contract : Bundle.TimelineReviewContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingTimelineReviewContract();
	return false;
}

bool UHyperTwistTrainingCaptureHistoryLibrary::TryGetComplianceBoundaryById(
	const FHyperTwistTrainingCaptureHistoryReferenceBundle& Bundle,
	const FString& BoundaryId,
	FHyperTwistTrainingCaptureHistoryComplianceBoundary& OutBoundary
)
{
	for (const FHyperTwistTrainingCaptureHistoryComplianceBoundary& Boundary : Bundle.ComplianceBoundaries)
	{
		if (Boundary.BoundaryId.Equals(BoundaryId, ESearchCase::IgnoreCase))
		{
			OutBoundary = Boundary;
			return true;
		}
	}

	OutBoundary = FHyperTwistTrainingCaptureHistoryComplianceBoundary();
	return false;
}

FString UHyperTwistTrainingCaptureHistoryLibrary::BuildPackageChecklistTsv(
	const FHyperTwistTrainingCaptureHistoryReferenceBundle& Bundle
)
{
	FString Output = TEXT("package_id\tlabel\tpackage_path\tusage_posture\tlicense_posture\tsummary\n");
	for (const FHyperTwistTrainingCaptureHistoryPackageReference& Reference : Bundle.PackageReferences)
	{
		if (!Reference.IsStructurallyValid())
		{
			continue;
		}

		Output.Append(Reference.PackageId);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.Label);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.PackagePath);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.UsagePosture);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.LicensePosture);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.Summary.Replace(TEXT("\t"), TEXT(" ")));
		Output.Append(TEXT("\n"));
	}

	return Output;
}
