using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEEDToolBox.Core.Data;
using XFEEDToolBox.Core.Execution;
using XFEEDToolBox.Core.Models;
internal static class RebuyReconciliation
{
internal static async Task RunAsync(int pid,string root)
{
root=Path.GetFullPath(root);using var hold=JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(root,"ship-loss-hold.json")));
var died=hold.RootElement.GetProperty("diedAt").GetDateTimeOffset();var before=hold.RootElement.GetProperty("lastConfirmedCredits").GetInt64();
var settings=ToolboxSettings.Load(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"XFEstudio","XFEEDToolBox","settings.json"));
await using var journal=new JournalMonitor(settings.JournalDirectory);await journal.StartAsync();var state=journal.State;
if(!state.InGame||!state.Docked||state.CurrentShipId!=5||state.CargoCount!=0)throw new InvalidOperationException("Rebuy reconciliation requires the docked original empty ship.");
var receipts=new List<(string Body,DateTimeOffset At,long Cost)>();
foreach(var file in Directory.EnumerateFiles(settings.JournalDirectory,"Journal*.log").Where(p=>File.GetLastWriteTimeUtc(p)>=died.UtcDateTime.Date))
{
string commander="";
using var stream=new FileStream(file,FileMode.Open,FileAccess.Read,FileShare.ReadWrite|FileShare.Delete);
using var reader=new StreamReader(stream);
while(reader.ReadLine() is {} line)
{
using var parsed=JsonDocument.Parse(line);var r=parsed.RootElement;var name=r.GetProperty("event").GetString();
if(name=="LoadGame")commander=r.GetProperty("FID").GetString()!;
if(name!="Resurrect"||commander!=state.CommanderId)continue;var at=r.GetProperty("timestamp").GetDateTimeOffset();if(at<=died)continue;
if(r.GetProperty("Option").GetString()!="rebuy"||r.GetProperty("Bankrupt").GetBoolean())throw new InvalidDataException("Unsupported recovery receipt.");
receipts.Add((line,at,r.GetProperty("Cost").GetInt64()));
}
}
if(receipts.Count!=1||receipts[0].Cost<=0)throw new InvalidDataException("Exactly one original paid rebuy receipt is required.");
var receipt=receipts[0];var inventory=await new NativeCommerceChannel(pid).CallAsync(new{op="commerce.inventory"},CancellationToken.None);
var after=inventory.GetProperty("credits").GetInt64();
if(!inventory.GetProperty("verified").GetBoolean()||inventory.GetProperty("count").GetInt32()!=0||inventory.GetProperty("capacity").GetInt32()!=192||before-receipt.Cost!=after)
throw new InvalidDataException("Original wallet does not reconcile with the recovery cost.");
var dir=Path.Combine(root,"recovery-costs","ship-loss-20261024");Directory.CreateDirectory(dir);using var ledger=new TradeProfitLedger(Path.Combine(dir,"ledger"));
var key="rebuy-"+Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(receipt.Body)));
ledger.Record(new(key,TradeCashKind.OtherExpense,receipt.Cost,state.MarketId??0,receipt.At));
await File.WriteAllTextAsync(Path.Combine(dir,"original-resurrect.json"),receipt.Body);
await File.WriteAllTextAsync(Path.Combine(dir,"result.json"),JsonSerializer.Serialize(new{passed=true,before,after,rebuyCost=receipt.Cost,profit=ledger.Snapshot,walletReconciled=true,ordersSubmitted=0},ToolboxSettings.JsonOptions));
var summaryPath=Path.Combine(root,"current-financial-summary.json");var summary=JsonNode.Parse(await File.ReadAllTextAsync(summaryPath))!.AsObject();
summary["confirmedNetProfit"]=hold.RootElement.GetProperty("confirmedNetProfitBeforeUnsettledLoss").GetInt64()-receipt.Cost;summary["credits"]=after;
summary["recoveryExpensePending"]=false;summary["netProfitFinal"]=true;summary["rebuyCost"]=receipt.Cost;summary["rebuyWalletReconciled"]=true;summary["at"]=DateTimeOffset.UtcNow.ToString("O");
var components=summary["components"]!.AsArray();if(!components.Any(x=>x?["directory"]?.GetValue<string>()=="recovery-costs/ship-loss-20261024"))
components.Add(new JsonObject{["directory"]="recovery-costs/ship-loss-20261024",["netProfit"]=-receipt.Cost});
await File.WriteAllTextAsync(summaryPath+".tmp",summary.ToJsonString(ToolboxSettings.JsonOptions));File.Move(summaryPath+".tmp",summaryPath,true);
Console.WriteLine(JsonSerializer.Serialize(new{rebuyCost=receipt.Cost,credits=after,confirmedNetProfit=summary["confirmedNetProfit"]!.GetValue<long>(),walletReconciled=true,ordersSubmitted=0}));
}
}
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEEDToolBox.Core.Data;
using XFEEDToolBox.Core.Execution;
using XFEEDToolBox.Core.Models;
internal static class RebuyReconciliation
{
internal static async Task RunAsync(int pid,string root)
{
root=Path.GetFullPath(root);using var hold=JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(root,"ship-loss-hold.json")));
var died=hold.RootElement.GetProperty("diedAt").GetDateTimeOffset();var before=hold.RootElement.GetProperty("lastConfirmedCredits").GetInt64();
var settings=ToolboxSettings.Load(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"XFEstudio","XFEEDToolBox","settings.json"));
await using var journal=new JournalMonitor(settings.JournalDirectory);await journal.StartAsync();var state=journal.State;
if(!state.InGame||!state.Docked||state.CurrentShipId!=5||state.CargoCount!=0)throw new InvalidOperationException("Rebuy reconciliation requires the docked original empty ship.");
var receipts=new List<(string Body,DateTimeOffset At,long Cost)>();
foreach(var file in Directory.EnumerateFiles(settings.JournalDirectory,"Journal*.log").Where(p=>File.GetLastWriteTimeUtc(p)>=died.UtcDateTime.Date))
{
string commander="";
using var stream=new FileStream(file,FileMode.Open,FileAccess.Read,FileShare.ReadWrite|FileShare.Delete);
using var reader=new StreamReader(stream);
while(reader.ReadLine() is {} line)
{
using var parsed=JsonDocument.Parse(line);var r=parsed.RootElement;var name=r.GetProperty("event").GetString();
if(name=="LoadGame")commander=r.GetProperty("FID").GetString()!;
if(name!="Resurrect"||commander!=state.CommanderId)continue;var at=r.GetProperty("timestamp").GetDateTimeOffset();if(at<=died)continue;
if(r.GetProperty("Option").GetString()!="rebuy"||r.GetProperty("Bankrupt").GetBoolean())throw new InvalidDataException("Unsupported recovery receipt.");
receipts.Add((line,at,r.GetProperty("Cost").GetInt64()));
}
}
if(receipts.Count!=1||receipts[0].Cost<=0)throw new InvalidDataException("Exactly one original paid rebuy receipt is required.");
var receipt=receipts[0];var inventory=await new NativeCommerceChannel(pid).CallAsync(new{op="commerce.inventory"},CancellationToken.None);
var after=inventory.GetProperty("credits").GetInt64();
if(!inventory.GetProperty("verified").GetBoolean()||inventory.GetProperty("count").GetInt32()!=0||inventory.GetProperty("capacity").GetInt32()!=192||before-receipt.Cost!=after)
throw new InvalidDataException("Original wallet does not reconcile with the recovery cost.");
var dir=Path.Combine(root,"recovery-costs","ship-loss-20261024");Directory.CreateDirectory(dir);using var ledger=new TradeProfitLedger(Path.Combine(dir,"ledger"));
var key="rebuy-"+Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(receipt.Body)));
ledger.Record(new(key,TradeCashKind.OtherExpense,receipt.Cost,state.MarketId??0,receipt.At));
await File.WriteAllTextAsync(Path.Combine(dir,"original-resurrect.json"),receipt.Body);
await File.WriteAllTextAsync(Path.Combine(dir,"result.json"),JsonSerializer.Serialize(new{passed=true,before,after,rebuyCost=receipt.Cost,profit=ledger.Snapshot,walletReconciled=true,ordersSubmitted=0},ToolboxSettings.JsonOptions));
var summaryPath=Path.Combine(root,"current-financial-summary.json");var summary=JsonNode.Parse(await File.ReadAllTextAsync(summaryPath))!.AsObject();
summary["confirmedNetProfit"]=hold.RootElement.GetProperty("confirmedNetProfitBeforeUnsettledLoss").GetInt64()-receipt.Cost;summary["credits"]=after;
summary["recoveryExpensePending"]=false;summary["netProfitFinal"]=true;summary["rebuyCost"]=receipt.Cost;summary["rebuyWalletReconciled"]=true;summary["at"]=DateTimeOffset.UtcNow.ToString("O");
var components=summary["components"]!.AsArray();if(!components.Any(x=>x?["directory"]?.GetValue<string>()=="recovery-costs/ship-loss-20261024"))
components.Add(new JsonObject{["directory"]="recovery-costs/ship-loss-20261024",["netProfit"]=-receipt.Cost});
await File.WriteAllTextAsync(summaryPath+".tmp",summary.ToJsonString(ToolboxSettings.JsonOptions));File.Move(summaryPath+".tmp",summaryPath,true);
Console.WriteLine(JsonSerializer.Serialize(new{rebuyCost=receipt.Cost,credits=after,confirmedNetProfit=summary["confirmedNetProfit"]!.GetValue<long>(),walletReconciled=true,ordersSubmitted=0}));
}
}