using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Core.Analysis;
using Titano.Core.Analysis.Deep;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Core.Video;
namespace Titano.Core.Advice;
///
/// A one-click bundle (BRIEF §10.3): full project settings plus an export preset, named by a resource key and
/// arguments (culture-neutral numbers or tokens) or, for user presets, by the user's own .
///
public sealed record SequencePreset
{
/// "night-sky", "holy-grail", "construction", "social-vertical", "standard", or a user id.
public required string Id { get; init; }
public required string NameKey { get; init; }
public IReadOnlyList NameArgs { get; init; } = [];
/// The user's name for a saved preset; overrides .
public string? Name { get; init; }
public string? ReasonKey { get; init; }
public IReadOnlyList ReasonArgs { get; init; } = [];
public required ProjectSettings Settings { get; init; }
public required string ExportPresetId { get; init; }
/// 0..1: how well the measured content matches the preset.
public double Confidence { get; init; }
public bool IsUser { get; init; }
public string DisplayName() => Name ?? Advisor.Explain(NameKey, NameArgs);
/// A copy saved under the user's name.
public SequencePreset AsUserPreset(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
return this with { Id = Guid.CreateVersion7().ToString("N"), Name = name.Trim(), IsUser = true };
}
public string ToJson() => JsonSerializer.Serialize(this, AdvisorJson.Default.SequencePreset);
public static SequencePreset FromJson(string json) =>
JsonSerializer.Deserialize(json, AdvisorJson.Default.SequencePreset) ?? throw new InvalidDataException("Preset JSON is empty.");
}
///
/// Generates the sequence presets that fit the measured content, best match first: Night sky (star field or night,
/// 4K 10-bit HEVC 24 fps, deflicker, stabilise when shaky), Holy grail sunset (received exposure steps across a
/// day/night change, 4K HEVC 30 fps, transitions), Construction cam (several sessions over at least a day, 1080p
/// H.264 30 fps, adaptive timing), Standard when none of these match, and Social vertical (1080×1920) always last.
/// A preset's export choice gives way to the advised one when the source, previews or encoders cannot reach it.
/// Content values stay Auto with the advisor's reasons; the preset's own choices are stored as manual values.
///
public static class SequencePresets
{
public static IReadOnlyList Generate(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context)
{
ArgumentNullException.ThrowIfNull(light);
ArgumentNullException.ThrowIfNull(context);
var advice = Advisor.Recommend(light, deep, context);
var advised = Advisor.Apply(new ProjectSettings(), advice);
var exportId = advice.Find(AdvisorParameters.ExportPreset)?.Value as string ?? "1080p-h264";
var presets = new List();
if (deep is { } d && (d.Sky.StarField || d.Sky.Light == DayNight.Night))
{
var id = Pick(exportId, "4k-hevc10-archive", context);
var window = advised.Exposure.DeflickerWindow.AutoValue;
var shaky = advice.Find(AdvisorParameters.Stabilize)?.Value is true;
var settings = Manual(advised, id, "24") with { Exposure = advised.Exposure with { Deflicker = advised.Exposure.Deflicker.WithManual(true) } };
if (shaky) settings = settings with { Motion = settings.Motion with { Stabilize = settings.Motion.Stabilize.WithManual(true) } };
var stars = d.Sky.StarField ? 100.0 * d.Sky.StarFrames / int.Max(1, d.FrameCount) : 0;
presets.Add(new SequencePreset
{
Id = "night-sky",
NameKey = shaky ? AdvisorKeys.PresetNightSkyStabilised : AdvisorKeys.PresetNightSky,
NameArgs = [Label(id), CodecLabel(id), "24", Text(window)],
ReasonKey = AdvisorKeys.PresetReasonNightSky,
ReasonArgs = [Text(double.Round(stars))],
Settings = settings,
ExportPresetId = id,
Confidence = d.Sky.StarField ? 0.9 : 0.7,
});
}
var received = deep?.Exposure.ReceivedSteps ?? (light.ExposureValues.Any(v => v is not null) ? light.ExposureSteps.Count : 0);
var lightChange = deep is not null
? deep.Sky.Light is DayNight.DayToNight or DayNight.NightToDay || deep.Exposure.SceneRangeEv >= 3
: light.Findings.Any(f => f.Key == FindingKeys.DayNightTransition);
if (received > 0 && lightChange)
{
var id = Pick(exportId, "4k-hevc", context);
var transitions = advised.Exposure.TransitionLength.AutoValue;
var range = deep?.Exposure.SceneRangeEv ?? 0;
var settings = Manual(advised, id, "30") with
{
Exposure = advised.Exposure with
{
HolyGrail = advised.Exposure.HolyGrail.WithManual(true),
Deflicker = advised.Exposure.Deflicker.WithManual(true),
},
};
presets.Add(new SequencePreset
{
Id = "holy-grail",
NameKey = AdvisorKeys.PresetHolyGrail,
NameArgs = [Label(id), CodecLabel(id), "30", Text(transitions)],
ReasonKey = AdvisorKeys.PresetReasonHolyGrail,
ReasonArgs = [Text(received), Text(double.Round(range, 1))],
Settings = settings,
ExportPresetId = id,
Confidence = 0.85,
});
}
if (light.Sessions.Count >= 2 && light.CaptureSpan >= TimeSpan.FromDays(1))
{
var id = Pick(exportId, "1080p-h264", context);
var settings = Manual(advised, id, "30");
settings = settings with { Timing = settings.Timing with { Mode = settings.Timing.Mode.WithManual(TimingMode.Adaptive) } };
presets.Add(new SequencePreset
{
Id = "construction",
NameKey = AdvisorKeys.PresetConstruction,
NameArgs = [Label(id), CodecLabel(id), "30"],
ReasonKey = AdvisorKeys.PresetReasonConstruction,
ReasonArgs = [Text(light.Sessions.Count), Text(double.Round(light.CaptureSpan.TotalDays, 1))],
Settings = settings,
ExportPresetId = id,
Confidence = 0.8,
});
}
if (presets.Count == 0)
{
var fps = advised.Timing.FrameRate.AutoValue ?? ExportPresets.Find(exportId)?.FrameRate.ToString() ?? "30";
presets.Add(new SequencePreset
{
Id = "standard",
NameKey = AdvisorKeys.PresetStandard,
NameArgs = [Label(exportId), CodecLabel(exportId), fps],
ReasonKey = AdvisorKeys.PresetReasonStandard,
Settings = Manual(advised, exportId, null),
ExportPresetId = exportId,
Confidence = 0.6,
});
}
const string vertical = "vertical-1080x1920";
var social = Manual(advised, vertical, "30") with { Camera = advised.Camera with { Aspect = advised.Camera.Aspect.WithManual("9:16"), OffsetY = 0 } };
presets.Add(new SequencePreset
{
Id = "social-vertical",
NameKey = AdvisorKeys.PresetSocialVertical,
NameArgs = ["1080", "1920"],
ReasonKey = AdvisorKeys.PresetReasonSocialVertical,
Settings = social,
ExportPresetId = vertical,
Confidence = 0.4,
});
return [.. presets.OrderByDescending(p => p.Confidence)];
}
/// The preset's own export choice when the advised size reaches 4K, else the advised (capped) preset.
private static string Pick(string advised, string wanted, SequenceContext context)
{
var cap = ExportPresets.Find(advised);
var target = ExportPresets.Find(wanted)!;
var codecOk = context.Codecs.Count == 0 || context.Codecs.Any(c => c.Codec == target.Codec && (target.BitDepth <= 8 || c.SupportsTenBit));
return cap is not null && cap.Width >= target.Width && cap.Height >= target.Height && codecOk ? wanted : advised;
}
/// Export preset and (optionally) frame rate as the preset's manual choices.
private static ProjectSettings Manual(ProjectSettings settings, string exportId, string? frameRate)
{
settings = settings with { Export = settings.Export with { Preset = settings.Export.Preset.WithManual(exportId) } };
return frameRate is null ? settings : settings with { Timing = settings.Timing with { FrameRate = settings.Timing.FrameRate.WithManual(frameRate) } };
}
/// Resolution label of an export preset ("4K", "1440p", "1080p", …).
private static string Label(string exportId) => ExportPresets.Find(exportId) switch
{
{ Width: >= 3840 } => "4K",
{ Width: > 0 } p => string.Create(CultureInfo.InvariantCulture, $"{int.Min(p.Width, p.Height)}p"),
_ => exportId,
};
/// Codec label of an export preset ("HEVC Main10", "HEVC", "H.264", "AV1"): technical names, not translated.
private static string CodecLabel(string exportId) => ExportPresets.Find(exportId) switch
{
{ Codec: VideoCodec.Hevc, BitDepth: >= 10 } => "HEVC Main10",
{ Codec: VideoCodec.Hevc } => "HEVC",
{ Codec: VideoCodec.Av1 } => "AV1",
{ Codec: VideoCodec.H264 } => "H.264",
{ } p => p.Codec.ToString(),
_ => exportId,
};
private static string Text(T value) => Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty;
}
/// Source-generated JSON for saved sequence presets.
[JsonSourceGenerationOptions(
WriteIndented = true,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true,
PropertyNameCaseInsensitive = true)]
[JsonSerializable(typeof(SequencePreset))]
internal sealed partial class AdvisorJson : JsonSerializerContext;