using System.Diagnostics;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Nodes;
using SopHelper.Engine.Sop;
using SopHelper.Engine.SopAgent;
using SopHelper.Training;
/// 真实服务测速:与界面相同,先生成,再基于当前草稿回测修订。
internal static class AgentBenchmarkChecks
{
public static async Task RunAsync(string configPath, string videoPath, string settingsPath, string reportPath,
string? sourceReportPath = null, bool verifyCurrentFirst = false, bool disableThinking = false, string? draftPath = null, int referenceStep = 0, bool replayOnly = false,
string? instructions = null, string? boundaryManifest = null)
{
Directory.CreateDirectory(reportPath);
using var settings = JsonDocument.Parse(File.ReadAllText(settingsPath));
var root = settings.RootElement;
// 测试进程已隔离 workspace;让回放和参考检查使用同一显式配置的多图服务,不修改用户设置。
var localSettings = JsonNode.Parse(root.GetRawText())!.AsObject();
localSettings["useForSequence"] = true;
if (disableThinking) localSettings["sequenceEnableThinking"] = false;
var isolatedSettings = Path.Combine(Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT") ?? throw new InvalidOperationException("实测必须使用隔离工作区"), "workspace", "sop-agent.json");
Directory.CreateDirectory(Path.GetDirectoryName(isolatedSettings)!);
File.WriteAllText(isolatedSettings, localSettings.ToJsonString());
string Text(string key) => root.TryGetProperty(key, out var v) ? v.GetString() ?? "" : "";
int Number(string key, int fallback) => root.TryGetProperty(key, out var v) ? v.GetInt32() : fallback;
double Decimal(string key, double fallback) => root.TryGetProperty(key, out var v) ? v.GetDouble() : fallback;
var connection = new SopAgentConnection(Text("endpoint"), Text("model"), Text("apiKey"),
Number("contextLength", 131702), Number("maxTokens", 8192), Decimal("temperature", .2), Decimal("topP", .9), Number("timeoutSeconds", 300),
disableThinking ? false : root.TryGetProperty("enableThinking", out var agentThinking) && agentThinking.ValueKind != JsonValueKind.Null ? agentThinking.GetBoolean() : null);
var template = SopConfigLoader.Load(configPath);
// 与界面未应用草稿的 CreateAgentVerificationTemplate 一致,不能继承不相关旧步骤的送检区。
template.Sop.Steps = [];
var original = File.ReadAllBytes(configPath);
var video = SopVideoSampler.ReadInfo(videoPath, default);
if (template.Sop.Regions.Values.Any(r => r.X1 < 0 || r.Y1 < 0 || r.X2 > video.Width || r.Y2 > video.Height))
throw new ArgumentException("测速配方区域超出当前视频尺寸,请选择匹配的现用配方");
using var handler = new MetricsHttp(reportPath, disableThinking);
using var http = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan };
using var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(15));
var timer = Stopwatch.StartNew();
var stage = "generate";
var prompts = new List