using System;
using System.Collections.Generic;
using KernelPanic.Core;
using KernelPanic.Data;
using KernelPanic.Meta;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
namespace KernelPanic.UI
{
/// Commits one pending pull, then hands its immutable receipt to the presentation.
[RequireComponent(typeof(UIDocument))]
public sealed class GamblingSceneController : MonoBehaviour
{
private VisualElement _root;
private GachaRevealView _view;
private void Awake()
{
_root = GetComponent().rootVisualElement;
_root.Clear();
_root.AddToClassList("gambling-root");
foreach (string resource in new[] { "RarityPresentation", "GamblingScene", "TerminalScrollbars" })
{
var sheet = Resources.Load(resource);
if (sheet != null) _root.styleSheets.Add(sheet);
}
TerminalTheme.Attach(_root);
}
private void Start()
{
// Consume once and save before any reveal controls become interactive.
if (!GachaPullContext.TryConsumePending(out PendingGachaPull pending))
{
_view = new GachaRevealView(_root,
new CompletedGachaPull(null, "git pull failed: no pending pull", Array.Empty()),
ContinueToMenu);
_view.Begin();
return;
}
CompletedGachaPull completed = ResolvePull(pending);
GachaPullContext.SetCompleted(completed);
_view = new GachaRevealView(_root, completed, ContinueToMenu);
_view.Begin();
}
private void OnDestroy() => _view?.Dispose();
private void ContinueToMenu()
{
SceneManager.LoadSceneAsync(SceneLoader.MainMenuSceneName);
}
private CompletedGachaPull ResolvePull(PendingGachaPull pending)
{
if (pending.DistroDatabase == null)
{
return new CompletedGachaPull(pending.BannerId, "git pull failed: distro database unavailable", Array.Empty());
}
SaveService saveService = new();
SaveData saveData = saveService.Load();
saveData.EnsureLists();
EntropyWallet wallet = new();
wallet.SetBalance(saveData.entropyBalance);
PlayerCollection collection = BuildCollection(saveData, pending.DistroDatabase, pending.PackageDatabase);
GachaService gacha = new();
RestoreBannerPool(gacha, saveData, pending.DistroDatabase);
gacha.LoadProgress(saveData);
PullPaymentSource paymentSource = pending.EntropyTokenCount > 0 ? PullPaymentSource.Entropy : PullPaymentSource.Commits;
GachaPullResult result = pending.BannerId switch
{
GachaService.BeginnerBannerId => gacha.PerformBeginnerPull(pending.PullCount, wallet, paymentSource),
GachaService.StandardBannerId => gacha.PerformStandardPull(pending.PullCount, wallet, paymentSource),
_ => GachaPullResult.Failed(pending.BannerId, "remote not implemented yet")
};
if (!result.Success)
{
return new CompletedGachaPull(pending.BannerId, $"git pull failed: {result.FailureReason}", Array.Empty());
}
List header = new()
{
result.EntropySpent > 0
? $"spent {result.EntropySpent} Entropy"
: $"spent {result.CurrencySpent} {GachaService.FormatCurrencyName(result.CurrencyType)}"
};
List distroRewards = new();
for (int i = 0; i < result.Rewards.Count; i++)
{
if (result.Rewards[i].Distro != null)
{
distroRewards.Add(result.Rewards[i].Distro);
}
}
PullResolutionResult resolution = PullResolver.Resolve(distroRewards, new PullResolutionContext(saveData, collection, pending.DistroDatabase, pending.FocusUnitId));
List completedRewards = new();
int distroOutcomeIndex = 0;
for (int i = 0; i < result.Rewards.Count; i++)
{
GachaReward reward = result.Rewards[i];
PullResolutionOutcome? outcome = null;
if (reward.Distro != null && resolution != null && distroOutcomeIndex < resolution.Outcomes.Count)
{
outcome = resolution.Outcomes[distroOutcomeIndex];
distroOutcomeIndex++;
}
PullOutcomeKind outcomeKind = outcome?.Kind ?? PullOutcomeKind.Invalid;
int merges = outcome?.MergesAwarded ?? 0;
IReadOnlyList languages = outcome?.LanguagesNewlyUnlocked ?? Array.Empty();
string displayName = reward.DisplayName;
PackageDefinition awardedPackage = null;
if (reward.RewardType == GachaRewardType.Package)
{
PackageDefinition package = GrantRandomPackageByRarity(pending.PackageDatabase, collection, saveData, reward.StarRating, out bool duplicatePackage, out int cacheAwarded);
awardedPackage = package;
if (package != null)
{
displayName = string.IsNullOrWhiteSpace(package.DisplayName) ? package.Id : package.DisplayName;
outcomeKind = duplicatePackage ? PullOutcomeKind.Dupe : PullOutcomeKind.Granted;
merges = cacheAwarded;
}
}
var display = new GachaRewardDisplayData(reward.Distro, awardedPackage,
reward.Distro == null ? 1 : collection.GetVersion(reward.Distro.Id),
awardedPackage == null ? 0 : collection.GetOwnedPackage(awardedPackage.Id)?.UpgradeLevel ?? 0);
completedRewards.Add(new CompletedGachaReward(i + 1, reward.StarRating, displayName, reward.RewardType, outcomeKind, merges, languages, reward.Guaranteed, reward.PityTriggered, display));
}
WriteState(saveService, saveData, wallet, collection, gacha);
return new CompletedGachaPull(result.BannerId, string.Join(" / ", header), completedRewards, gacha.PendingStandardFiveStarSelectors);
}
private static PlayerCollection BuildCollection(SaveData saveData, DistroDatabase distroDatabase, PackageDatabase packageDatabase)
{
PlayerCollection collection = new();
for (int i = 0; i < saveData.ownedUnits.Count; i++)
{
OwnedUnitSaveEntry entry = saveData.ownedUnits[i];
DistroDefinition unit = entry == null ? null : distroDatabase.FindById(entry.id);
if (unit != null)
{
collection.AddSilently(unit, entry.version);
}
}
for (int i = 0; i < saveData.ownedPackages.Count; i++)
{
OwnedPackageSaveEntry entry = saveData.ownedPackages[i];
PackageDefinition package = packageDatabase == null ? null : packageDatabase.FindById(entry?.id);
if (package != null)
{
collection.AddPackageSilently(package, entry.upgradeLevel);
}
}
return collection;
}
private static PackageDefinition GrantRandomPackageByRarity(PackageDatabase packageDatabase, PlayerCollection collection, SaveData saveData, int rarity, out bool duplicate, out int cacheAwarded)
{
duplicate = false;
cacheAwarded = 0;
int count = packageDatabase == null ? 0 : packageDatabase.CountByRarity(rarity);
if (count <= 0)
{
return null;
}
int index = UnityEngine.Random.Range(0, count);
PackageDefinition package = packageDatabase.FindByRarity(rarity, index);
if (package == null)
{
return null;
}
duplicate = collection.IsPackageOwned(package.Id);
if (duplicate)
{
// Packages are unique-per-type: a dupe never creates a second instance, it
// auto-scraps into Cache immediately, mirroring the distro dupe -> Merges path.
cacheAwarded = PackageTuning.GetCacheForRarity(package.Rarity);
saveData.cacheBalance += cacheAwarded;
}
else
{
collection.AddPackageSilently(package);
saveData.ownedPackages.Add(new OwnedPackageSaveEntry { id = package.Id, upgradeLevel = 0 });
saveData.ownedPackageIds.Add(package.Id);
}
return package;
}
private static void RestoreBannerPool(GachaService gacha, SaveData saveData, DistroDatabase distroDatabase)
{
for (int i = 0; i < saveData.bannerPoolIds.Count; i++)
{
DistroDefinition unit = distroDatabase.FindById(saveData.bannerPoolIds[i]);
if (unit != null)
{
gacha.AddToBannerPool(unit);
}
}
if (saveData.starterChosen)
{
IReadOnlyList distros = distroDatabase.AllDistros;
for (int i = 0; i < distros.Count; i++)
{
DistroDefinition distro = distros[i];
if (GachaService.IsBeginnerInstallMediaDistro(distro))
{
gacha.AddToBannerPool(distro);
}
}
}
}
private static void WriteState(SaveService saveService, SaveData saveData, EntropyWallet wallet, PlayerCollection collection, GachaService gacha)
{
Dictionary mergeBalances = new(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < saveData.ownedUnits.Count; i++)
{
OwnedUnitSaveEntry entry = saveData.ownedUnits[i];
if (entry != null && !string.IsNullOrWhiteSpace(entry.id))
{
mergeBalances[entry.id] = Math.Max(0, entry.merges);
}
}
saveData.entropyBalance = wallet.Balance;
saveData.ownedUnits.Clear();
saveData.ownedPackages.Clear();
saveData.ownedPackageIds.Clear();
saveData.ownedUnitIds.Clear();
saveData.bannerPoolIds.Clear();
gacha.WriteProgress(saveData);
for (int i = 0; i < collection.OwnedUnits.Count; i++)
{
DistroDefinition unit = collection.OwnedUnits[i];
if (unit != null && !string.IsNullOrWhiteSpace(unit.Id))
{
saveData.ownedUnits.Add(new OwnedUnitSaveEntry
{
id = unit.Id,
version = Mathf.Clamp(collection.GetVersion(unit.Id), 1, GachaTuning.MaxVersion),
merges = mergeBalances.TryGetValue(unit.Id, out int merges) ? merges : 0
});
}
}
for (int i = 0; i < collection.OwnedPackageInstances.Count; i++)
{
OwnedPackageInstance package = collection.OwnedPackageInstances[i];
if (package != null && !string.IsNullOrWhiteSpace(package.PackageId))
{
saveData.ownedPackages.Add(new OwnedPackageSaveEntry { id = package.PackageId, upgradeLevel = package.UpgradeLevel });
saveData.ownedPackageIds.Add(package.PackageId);
}
}
for (int i = 0; i < gacha.BannerPool.Count; i++)
{
DistroDefinition unit = gacha.BannerPool[i];
if (unit != null && !string.IsNullOrWhiteSpace(unit.Id))
{
saveData.bannerPoolIds.Add(unit.Id);
}
}
saveService.Save(saveData);
}
}
}