#include "HyperTwistTraining/HyperTwistTrainingLegacy4DLibrary.h"

namespace HyperTwistTrainingLegacy4DLibraryInternal
{
	const TCHAR* MagicCube4DLicense = TEXT("custom permissive attribution-request license");

	FHyperTwistTrainingSourceAttribution MakeAttribution(
		const FString& TrackId,
		const FString& Notes
	)
	{
		FHyperTwistTrainingSourceAttribution Attribution;
		Attribution.SourceMode = EHyperTwistTrainingSourceMode::DirectDonor;
		Attribution.SourceRepo = TEXT("cutelyaware/magiccube4d");
		Attribution.SourceLicense = MagicCube4DLicense;
		Attribution.SourceTrackId = TrackId;
		Attribution.SourceNotes = Notes;
		return Attribution;
	}

	FHyperTwistTrainingLegacy4DPackageReference MakePackageReference(
		const FString& PackageId,
		const FString& Label,
		const FString& ExportPath,
		const FString& OwnershipRole,
		const FString& LicensePosture,
		const FString& Summary,
		const TArray<FString>& RetainedSurfaceTags,
		const TArray<FString>& RequiredNoticeActions,
		const TArray<FString>& ExplicitExclusions,
		const FHyperTwistTrainingSourceAttribution& SourceAttribution
	)
	{
		FHyperTwistTrainingLegacy4DPackageReference Reference;
		Reference.PackageId = PackageId;
		Reference.Label = Label;
		Reference.ExportPath = ExportPath;
		Reference.OwnershipRole = OwnershipRole;
		Reference.LicensePosture = LicensePosture;
		Reference.Summary = Summary;
		Reference.RetainedSurfaceTags = RetainedSurfaceTags;
		Reference.RequiredNoticeActions = RequiredNoticeActions;
		Reference.ExplicitExclusions = ExplicitExclusions;
		Reference.SourceAttribution = SourceAttribution;
		return Reference;
	}

	void AppendJoined(FString& OutText, const TArray<FString>& Values)
	{
		for (int32 Index = 0; Index < Values.Num(); ++Index)
		{
			if (Index > 0)
			{
				OutText.Append(TEXT(", "));
			}

			OutText.Append(Values[Index]);
		}
	}
}

FHyperTwistTrainingLegacy4DReferenceBundle
UHyperTwistTrainingLegacy4DLibrary::BuildBundledLegacy4DReferenceBundle()
{
	using namespace HyperTwistTrainingLegacy4DLibraryInternal;

	FHyperTwistTrainingLegacy4DReferenceBundle Bundle;
	Bundle.ReferenceUtc = TEXT("2026-05-13T23:00:00Z");
	Bundle.PrimaryHistoryContractId = TEXT("legacy-4d-history-stack");
	Bundle.PrimaryMacroContractId = TEXT("legacy-4d-macro-stack");
	Bundle.PrimaryPuzzleDescriptionContractId = TEXT("legacy-4d-puzzle-description-stack");
	Bundle.PrimaryInteractionContractId = TEXT("legacy-4d-interaction-stack");
	Bundle.PrimaryAttributionBoundaryId = TEXT("legacy-4d-attribution-boundary");

	const TArray<FString> CommonNoticeActions =
	{
		TEXT("preserve the upstream copyright notice in third-party notices or equivalent release/legal materials"),
		TEXT("provide natural product-facing attribution for MagicCube4D"),
		TEXT("include a link to http://superliminal.com/cube/cube.htm in attribution materials"),
		TEXT("preserve the upstream license text in distributed legal materials"),
		TEXT("keep the MyMath provenance note visible if related numeric helpers are closely adapted")
	};

	Bundle.PackageReferences =
	{
		MakePackageReference(
			TEXT("package/magiccube4d-history"),
			TEXT("magiccube4d/History"),
			TEXT("./src/com/superliminal/magiccube4d/History.java"),
			TEXT("legacy-history-anchor"),
			TEXT("attributed strategic donor"),
			TEXT("Move-log, mark, macro-boundary, undo-redo, and save-restore substrate for owned HyperTwist higher-dimensional history and review flows."),
			{
				TEXT("history nodes"),
				TEXT("marks and macro brackets"),
				TEXT("undo redo traversal"),
				TEXT("save restore log format")
			},
			CommonNoticeActions,
			{
				TEXT("whole Java shell ownership"),
				TEXT("Swing app-shell ownership"),
				TEXT("direct donor UI transplant")
			},
			MakeAttribution(
				TEXT("legacy-4d/history"),
				TEXT("Preserves move-log, mark, macro-boundary, undo-redo, and save-restore semantics from MagicCube4D beneath first-party HyperTwist history and review ownership.")
			)
		),
		MakePackageReference(
			TEXT("package/magiccube4d-macro"),
			TEXT("magiccube4d/Macro"),
			TEXT("./src/com/superliminal/magiccube4d/Macro.java"),
			TEXT("legacy-macro-anchor"),
			TEXT("attributed strategic donor"),
			TEXT("Reference-grip macro remapping, transform application, and reversal substrate for owned HyperTwist higher-dimensional macro and teaching flows."),
			{
				TEXT("reference grips"),
				TEXT("4D transform remapping"),
				TEXT("macro reversal"),
				TEXT("macro serialization")
			},
			CommonNoticeActions,
			{
				TEXT("whole macro editor shell ownership"),
				TEXT("legacy file format lock-in"),
				TEXT("direct donor UI transplant")
			},
			MakeAttribution(
				TEXT("legacy-4d/macro"),
				TEXT("Preserves reference-grip macro remapping, transform application, reversal, and serialization seams from MagicCube4D for first-party HyperTwist higher-dimensional macro flows.")
			)
		),
		MakePackageReference(
			TEXT("package/magiccube4d-polytope-puzzle-description"),
			TEXT("magiccube4d/PolytopePuzzleDescription"),
			TEXT("./src/com/superliminal/magiccube4d/PolytopePuzzleDescription.java"),
			TEXT("legacy-geometry-reference"),
			TEXT("attributed strategic donor"),
			TEXT("Legacy generic polytope slicing, grip-sticker-face relationship, and Schlafli-product puzzle-description substrate for owned HyperTwist topology adapters."),
			{
				TEXT("Schlafli product parsing"),
				TEXT("polytope slicing"),
				TEXT("grip to face mapping"),
				TEXT("face cut offsets"),
				TEXT("sticker and cubie relationships")
			},
			CommonNoticeActions,
			{
				TEXT("Hyperspeedcube replacement"),
				TEXT("legacy app-shell ownership"),
				TEXT("copying TODOs as first-party roadmap")
			},
			MakeAttribution(
				TEXT("legacy-4d/puzzle-description"),
				TEXT("Preserves generic polytope slicing, grip-sticker-face relationships, and Schlafli-product puzzle-description seams from MagicCube4D without displacing the Hyperspeedcube runtime anchor.")
			)
		),
		MakePackageReference(
			TEXT("package/magiccube4d-rotation-handler"),
			TEXT("magiccube4d/RotationHandler"),
			TEXT("./src/com/superliminal/magiccube4d/RotationHandler.java"),
			TEXT("legacy-4d-rotation-grammar"),
			TEXT("attributed strategic donor"),
			TEXT("4D rotation-state, snap-to-center, spin continuation, and drag-grammar substrate for owned HyperTwist higher-dimensional interaction flows."),
			{
				TEXT("4D view matrix state"),
				TEXT("snap to center"),
				TEXT("spin continuation"),
				TEXT("drag grammar")
			},
			CommonNoticeActions,
			{
				TEXT("whole input shell ownership"),
				TEXT("legacy property-manager dependency"),
				TEXT("direct utility transplant")
			},
			MakeAttribution(
				TEXT("legacy-4d/rotation-handler"),
				TEXT("Preserves 4D rotation-state, snap semantics, spin continuation, and drag grammar from MagicCube4D beneath first-party HyperTwist interaction ownership.")
			)
		),
		MakePackageReference(
			TEXT("package/magiccube4d-view"),
			TEXT("magiccube4d/MC4DView"),
			TEXT("./src/com/superliminal/magiccube4d/MC4DView.java"),
			TEXT("legacy-view-controller-reference"),
			TEXT("attributed strategic donor"),
			TEXT("Animation-queue, picking, highlighting, slice-mask, and viewer-controller composition substrate for owned HyperTwist higher-dimensional sidecars."),
			{
				TEXT("animation queue"),
				TEXT("sticker picking"),
				TEXT("sticker highlighting"),
				TEXT("slice mask"),
				TEXT("viewer controller composition")
			},
			CommonNoticeActions,
			{
				TEXT("Swing component transplant"),
				TEXT("legacy event-shell ownership"),
				TEXT("whole donor viewer shell")
			},
			MakeAttribution(
				TEXT("legacy-4d/view"),
				TEXT("Preserves animation-queue, sticker-picking, highlight, slice-mask, and viewer-controller seams from MagicCube4D for first-party HyperTwist higher-dimensional sidecars.")
			)
		),
		MakePackageReference(
			TEXT("package/magiccube4d-mymath-selective-reference"),
			TEXT("donhatchsw/util/MyMath"),
			TEXT("./src/com/donhatchsw/util/MyMath.java"),
			TEXT("selective-math-provenance-reference"),
			TEXT("attributed strategic donor with provenance caveat"),
			TEXT("Selective numeric reference surface for legacy projection and interaction parity, with an explicit provenance caveat on one documented log1p note."),
			{
				TEXT("numeric helper parity"),
				TEXT("projection helper reference"),
				TEXT("provenance note retention")
			},
			CommonNoticeActions,
			{
				TEXT("wholesale utility transplant"),
				TEXT("pretending the file is a plain zero-friction utility import"),
				TEXT("copying math helpers without provenance discipline")
			},
			MakeAttribution(
				TEXT("legacy-4d/mymath-provenance"),
				TEXT("Records the selective math-helper provenance caveat noted in MagicCube4D without promoting MyMath into HyperTwist's default first-party math stack.")
			)
		)
	};

	FHyperTwistTrainingLegacy4DHistoryContract HistoryContract;
	HistoryContract.ContractId = TEXT("legacy-4d-history-stack");
	HistoryContract.Title = TEXT("Legacy 4D history, marks, and save-restore contract");
	HistoryContract.Summary = TEXT("First-party HyperTwist contract for higher-dimensional move logs, mark boundaries, undo-redo traversal, macro delimiters, and persisted replay-history semantics informed by MagicCube4D.");
	HistoryContract.RequiredPackageIds =
	{
		TEXT("package/magiccube4d-history"),
		TEXT("package/magiccube4d-macro")
	};
	HistoryContract.HistorySurfaceTags =
	{
		TEXT("history nodes"),
		TEXT("current-node traversal"),
		TEXT("undo redo"),
		TEXT("truncate"),
		TEXT("move enumeration")
	};
	HistoryContract.MarkKinds =
	{
		TEXT("macro open and close"),
		TEXT("scramble boundary"),
		TEXT("setup moves"),
		TEXT("arbitrary bookmark marks")
	};
	HistoryContract.SerializationSurfaceTags =
	{
		TEXT("save restore log format"),
		TEXT("mark-aware persistence"),
		TEXT("macro-boundary persistence")
	};
	HistoryContract.ExplicitExclusions =
	{
		TEXT("whole Java shell ownership"),
		TEXT("legacy menu system"),
		TEXT("direct donor UI state management")
	};
	HistoryContract.SourceAttribution = MakeAttribution(
		TEXT("legacy-4d/history-contract"),
		TEXT("Preserves MagicCube4D history-node, mark, undo-redo, and persisted replay semantics beneath first-party HyperTwist higher-dimensional history ownership.")
	);
	Bundle.HistoryContracts = {HistoryContract};

	FHyperTwistTrainingLegacy4DMacroContract MacroContract;
	MacroContract.ContractId = TEXT("legacy-4d-macro-stack");
	MacroContract.Title = TEXT("Legacy 4D macro remapping and reversal contract");
	MacroContract.Summary = TEXT("First-party HyperTwist contract for reference-grip macro capture, 4D transform remapping, reversal, and macro playback semantics for higher-dimensional teaching flows.");
	MacroContract.RequiredPackageIds =
	{
		TEXT("package/magiccube4d-macro"),
		TEXT("package/magiccube4d-history"),
		TEXT("package/magiccube4d-polytope-puzzle-description")
	};
	MacroContract.ReferenceSurfaceTags =
	{
		TEXT("definition grips"),
		TEXT("application grips"),
		TEXT("face-center references"),
		TEXT("puzzle-specific macro ownership")
	};
	MacroContract.TransformSurfaceTags =
	{
		TEXT("4D rotation transform derivation"),
		TEXT("closest grip remapping"),
		TEXT("determinant-based reverse handling"),
		TEXT("macro serialization")
	};
	MacroContract.PlaybackSurfaceTags =
	{
		TEXT("macro move list"),
		TEXT("macro undo and truncate"),
		TEXT("macro write and read")
	};
	MacroContract.ExplicitExclusions =
	{
		TEXT("whole macro editor shell"),
		TEXT("legacy persistence lock-in"),
		TEXT("donor menu choreography")
	};
	MacroContract.SourceAttribution = MakeAttribution(
		TEXT("legacy-4d/macro-contract"),
		TEXT("Preserves MagicCube4D reference-grip macro remapping, reversal, and serialization semantics for first-party HyperTwist higher-dimensional macro flows.")
	);
	Bundle.MacroContracts = {MacroContract};

	FHyperTwistTrainingLegacy4DPuzzleDescriptionContract PuzzleDescriptionContract;
	PuzzleDescriptionContract.ContractId = TEXT("legacy-4d-puzzle-description-stack");
	PuzzleDescriptionContract.Title = TEXT("Legacy 4D puzzle-description and topology contract");
	PuzzleDescriptionContract.Summary = TEXT("First-party HyperTwist contract for generic polytope slicing, Schlafli-product puzzle-description parsing, and grip-sticker-face topology seams informed by MagicCube4D.");
	PuzzleDescriptionContract.RequiredPackageIds =
	{
		TEXT("package/magiccube4d-polytope-puzzle-description"),
		TEXT("package/magiccube4d-mymath-selective-reference")
	};
	PuzzleDescriptionContract.PuzzleFamilies =
	{
		TEXT("generic Schlafli-product families"),
		TEXT("hypercubes and simplices"),
		TEXT("120-cell and related 4D families"),
		TEXT("prisms and duoprisms"),
		TEXT("Melinda 2x2x2x2-adjacent legacy references")
	};
	PuzzleDescriptionContract.GeometrySurfaceTags =
	{
		TEXT("Schlafli product parsing"),
		TEXT("polytope slicing"),
		TEXT("sticker center hashing"),
		TEXT("face cut offsets"),
		TEXT("grip center and face-center relationships")
	};
	PuzzleDescriptionContract.TopologySurfaceTags =
	{
		TEXT("sticker to face mapping"),
		TEXT("sticker to cubie mapping"),
		TEXT("grip to face mapping"),
		TEXT("face opposites"),
		TEXT("contiguous topology caveats")
	};
	PuzzleDescriptionContract.ExplicitExclusions =
	{
		TEXT("Hyperspeedcube replacement"),
		TEXT("legacy applet shell ownership"),
		TEXT("copying historical TODOs as first-party roadmap")
	};
	PuzzleDescriptionContract.SourceAttribution = MakeAttribution(
		TEXT("legacy-4d/puzzle-description-contract"),
		TEXT("Preserves MagicCube4D generic polytope slicing and topology seams without displacing the Hyperspeedcube higher-dimensional runtime anchor.")
	);
	Bundle.PuzzleDescriptionContracts = {PuzzleDescriptionContract};

	FHyperTwistTrainingLegacy4DInteractionContract InteractionContract;
	InteractionContract.ContractId = TEXT("legacy-4d-interaction-stack");
	InteractionContract.Title = TEXT("Legacy 4D interaction, picking, and animation contract");
	InteractionContract.Summary = TEXT("First-party HyperTwist contract for 4D rotation grammar, snap behavior, sticker picking, highlight state, slice masks, and animation-queue semantics informed by MagicCube4D.");
	InteractionContract.RequiredPackageIds =
	{
		TEXT("package/magiccube4d-rotation-handler"),
		TEXT("package/magiccube4d-view"),
		TEXT("package/magiccube4d-polytope-puzzle-description")
	};
	InteractionContract.RotationSurfaceTags =
	{
		TEXT("4D view matrix state"),
		TEXT("snap to cell or smart center"),
		TEXT("spin continuation"),
		TEXT("left shift right drag grammar")
	};
	InteractionContract.ViewSurfaceTags =
	{
		TEXT("sticker picking"),
		TEXT("sticker highlighting"),
		TEXT("slice mask state"),
		TEXT("viewer controller composition"),
		TEXT("listener callbacks")
	};
	InteractionContract.AnimationSurfaceTags =
	{
		TEXT("queued animation"),
		TEXT("macro move flagging"),
		TEXT("callback completion"),
		TEXT("cancel animation"),
		TEXT("highlight refresh during motion")
	};
	InteractionContract.ExplicitExclusions =
	{
		TEXT("Swing component transplant"),
		TEXT("whole donor event shell"),
		TEXT("legacy property-manager dependency")
	};
	InteractionContract.SourceAttribution = MakeAttribution(
		TEXT("legacy-4d/interaction-contract"),
		TEXT("Preserves MagicCube4D 4D rotation grammar, sticker picking, slice-mask, and animation-queue seams beneath first-party HyperTwist higher-dimensional interaction ownership.")
	);
	Bundle.InteractionContracts = {InteractionContract};

	FHyperTwistTrainingLegacy4DAttributionBoundary AttributionBoundary;
	AttributionBoundary.BoundaryId = TEXT("legacy-4d-attribution-boundary");
	AttributionBoundary.Title = TEXT("Legacy 4D attribution and provenance boundary");
	AttributionBoundary.Summary = TEXT("First-party HyperTwist compliance boundary for using MagicCube4D as an attributed strategic donor, preserving notices, visible attribution, upstream link requirements, and the documented MyMath provenance caveat.");
	AttributionBoundary.AllowedUseTags =
	{
		TEXT("first-party reauthored subsystem implementation"),
		TEXT("attributed strategic donor reference"),
		TEXT("bounded reference bundle and runtime contract use"),
		TEXT("selective reauthored numeric helper parity with provenance discipline")
	};
	AttributionBoundary.RequiredNoticeActions = CommonNoticeActions;
	AttributionBoundary.ProvenanceCaveats =
	{
		TEXT("keep visible attribution to Superliminal Software and the MagicCube4D lineage"),
		TEXT("do not treat the custom license as a silent plain-MIT import"),
		TEXT("record the MyMath log1p provenance note rather than erasing it"),
		TEXT("preserve the upstream site link requirement in product-facing attribution materials")
	};
	AttributionBoundary.ExplicitExclusions =
	{
		TEXT("silent attribution removal"),
		TEXT("whole legacy Java shell adoption"),
		TEXT("wholesale MyMath transplant without provenance discipline"),
		TEXT("treating MagicCube4D as the HyperTwist runtime owner")
	};
	AttributionBoundary.SourceAttribution = MakeAttribution(
		TEXT("legacy-4d/attribution-boundary"),
		TEXT("Preserves MagicCube4D attribution, notice, link, and MyMath provenance obligations while keeping the landed HyperTwist higher-dimensional lane first-party and bounded.")
	);
	Bundle.AttributionBoundaries = {AttributionBoundary};

	return Bundle;
}

bool UHyperTwistTrainingLegacy4DLibrary::TryGetHistoryContractById(
	const FHyperTwistTrainingLegacy4DReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingLegacy4DHistoryContract& OutContract
)
{
	for (const FHyperTwistTrainingLegacy4DHistoryContract& Contract : Bundle.HistoryContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingLegacy4DHistoryContract();
	return false;
}

bool UHyperTwistTrainingLegacy4DLibrary::TryGetMacroContractById(
	const FHyperTwistTrainingLegacy4DReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingLegacy4DMacroContract& OutContract
)
{
	for (const FHyperTwistTrainingLegacy4DMacroContract& Contract : Bundle.MacroContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingLegacy4DMacroContract();
	return false;
}

bool UHyperTwistTrainingLegacy4DLibrary::TryGetPuzzleDescriptionContractById(
	const FHyperTwistTrainingLegacy4DReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingLegacy4DPuzzleDescriptionContract& OutContract
)
{
	for (const FHyperTwistTrainingLegacy4DPuzzleDescriptionContract& Contract : Bundle.PuzzleDescriptionContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingLegacy4DPuzzleDescriptionContract();
	return false;
}

bool UHyperTwistTrainingLegacy4DLibrary::TryGetInteractionContractById(
	const FHyperTwistTrainingLegacy4DReferenceBundle& Bundle,
	const FString& ContractId,
	FHyperTwistTrainingLegacy4DInteractionContract& OutContract
)
{
	for (const FHyperTwistTrainingLegacy4DInteractionContract& Contract : Bundle.InteractionContracts)
	{
		if (Contract.ContractId.Equals(ContractId, ESearchCase::IgnoreCase))
		{
			OutContract = Contract;
			return true;
		}
	}

	OutContract = FHyperTwistTrainingLegacy4DInteractionContract();
	return false;
}

bool UHyperTwistTrainingLegacy4DLibrary::TryGetAttributionBoundaryById(
	const FHyperTwistTrainingLegacy4DReferenceBundle& Bundle,
	const FString& BoundaryId,
	FHyperTwistTrainingLegacy4DAttributionBoundary& OutBoundary
)
{
	for (const FHyperTwistTrainingLegacy4DAttributionBoundary& Boundary : Bundle.AttributionBoundaries)
	{
		if (Boundary.BoundaryId.Equals(BoundaryId, ESearchCase::IgnoreCase))
		{
			OutBoundary = Boundary;
			return true;
		}
	}

	OutBoundary = FHyperTwistTrainingLegacy4DAttributionBoundary();
	return false;
}

FString UHyperTwistTrainingLegacy4DLibrary::BuildPackageChecklistTsv(
	const FHyperTwistTrainingLegacy4DReferenceBundle& Bundle
)
{
	using namespace HyperTwistTrainingLegacy4DLibraryInternal;

	FString Output = TEXT("package_id\tlabel\texport_path\townership_role\tlicense_posture\tretained_surfaces\tsummary\n");
	for (const FHyperTwistTrainingLegacy4DPackageReference& Reference : Bundle.PackageReferences)
	{
		if (!Reference.IsStructurallyValid())
		{
			continue;
		}

		FString SurfaceTags;
		AppendJoined(SurfaceTags, Reference.RetainedSurfaceTags);

		Output.Append(Reference.PackageId);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.Label);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.ExportPath);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.OwnershipRole);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.LicensePosture);
		Output.Append(TEXT("\t"));
		Output.Append(SurfaceTags);
		Output.Append(TEXT("\t"));
		Output.Append(Reference.Summary.Replace(TEXT("\t"), TEXT(" ")));
		Output.Append(TEXT("\n"));
	}

	return Output;
}
