using System.IO;
using System.Net;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Protocol;
using Titano.Protocol.Client;
namespace Titano.App.Import;
///
/// Import destination "Server" (BRIEF §12.4, §14.4): each verified copy staged on this PC is uploaded with the
/// protocol's resumable chunks and the hash computed while copying; the server checks that hash before it commits the
/// frame, and only then does the photo count as imported. Photos of one plan session share its session key, so the
/// server files them in one sequence — the same one when an interrupted import is started again. A typed session
/// title is set on that sequence once. A file the server refuses (a hash mismatch, a format it rejects) is listed in
/// and the import goes on (BRIEF §13: errors per file); a failed connection, sign-in or server
/// stops it.
///
public sealed class ServerImportSink(TitanoClient client, string stagingDirectory) : IImportSink
{
private readonly HashSet _titled = [];
public string StagingDirectory { get; } = stagingDirectory;
/// Every file committed or refused so far, by card path; pass it to .
public ImportSinkReport Report { get; } = new();
public async Task> CommitAsync(PlannedSession session, IReadOnlyList files, CancellationToken cancellationToken)
{
var results = new List(files.Count);
foreach (var file in files)
{
// The server records the uploaded file name as the original name: upload the card's name, not the staging name.
var folder = Path.Combine(StagingDirectory, Path.GetFileNameWithoutExtension(file.StagedPath));
var named = Path.Combine(folder, Path.GetFileName(file.Item.SourcePath));
Directory.CreateDirectory(folder);
File.Move(file.StagedPath, named);
CompleteUploadResponse? committed = null;
try
{
committed = await client.UploadFileAsync(named, null, file.Item.CapturedAt, session.SessionKey, file.Sha256, null, cancellationToken)
.ConfigureAwait(false);
// An upload the server already held reports no position in a sequence.
var result = new SinkCommit(committed?.FrameId, file.Item.FileName, committed is null || committed.Index < 0);
Report.Committed[file.Item.SourcePath] = result;
results.Add(result);
}
catch (TitanoApiException ex) when (IsRefusal(ex))
{
// The executor has no failed commit: the refusal travels in the report, which turns this result into a failure.
Report.Rejected[file.Item.SourcePath] = ex.Error.Message;
results.Add(new SinkCommit(null, file.Item.FileName, Duplicate: false));
}
finally
{
// Our own staged copy; the original stays on the card.
File.Delete(named);
Directory.Delete(folder);
}
if (committed is { Index: >= 0 } && session.Title is { Length: > 0 } title && _titled.Add(committed.SequenceId))
await SetTitleAsync(committed.SequenceId, title, cancellationToken).ConfigureAwait(false);
}
return results;
}
/// A refused title leaves the photos imported under the sequence's own name.
private async Task SetTitleAsync(Guid sequenceId, string title, CancellationToken cancellationToken)
{
try
{
await client.UpdateSequenceAsync(sequenceId, new UpdateSequenceRequest(title, null, null, null, null, null), cancellationToken).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (IsRefusal(ex))
{
Log.Warning("import", $"The server refused the title of sequence {sequenceId}", ex);
}
}
/// The server refused this file; other files may still go through (unlike a busy server or a lost sign-in).
private static bool IsRefusal(TitanoApiException ex) =>
!ex.IsTransient && ex.Status is not (HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) && (int)ex.Status is >= 400 and < 500;
}