using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;

namespace StellaOps.Vexer.Core;

/// <summary>
/// Shared connector contract for fetching and normalizing provider-specific VEX data.
/// </summary>
public interface IVexConnector
{
    string Id { get; }

    VexProviderKind Kind { get; }

    ValueTask ValidateAsync(VexConnectorSettings settings, CancellationToken cancellationToken);

    IAsyncEnumerable<VexRawDocument> FetchAsync(VexConnectorContext context, CancellationToken cancellationToken);

    ValueTask<VexClaimBatch> NormalizeAsync(VexRawDocument document, CancellationToken cancellationToken);
}

/// <summary>
/// Connector context populated by the orchestrator/worker.
/// </summary>
public sealed record VexConnectorContext(
    DateTimeOffset? Since,
    VexConnectorSettings Settings,
    IVexRawDocumentSink RawSink,
    IVexSignatureVerifier SignatureVerifier,
    IVexNormalizerRouter Normalizers,
    IServiceProvider Services);

/// <summary>
/// Normalized connector configuration values.
/// </summary>
public sealed record VexConnectorSettings(ImmutableDictionary<string, string> Values)
{
    public static VexConnectorSettings Empty { get; } = new(ImmutableDictionary<string, string>.Empty);
}

/// <summary>
/// Raw document retrieved from a connector pull.
/// </summary>
public sealed record VexRawDocument(
    string ProviderId,
    VexDocumentFormat Format,
    Uri SourceUri,
    DateTimeOffset RetrievedAt,
    string Digest,
    ReadOnlyMemory<byte> Content,
    ImmutableDictionary<string, string> Metadata)
{
    public Guid DocumentId { get; init; } = Guid.NewGuid();
}

/// <summary>
/// Batch of normalized claims derived from a raw document.
/// </summary>
public sealed record VexClaimBatch(
    VexRawDocument Source,
    ImmutableArray<VexClaim> Claims,
    ImmutableDictionary<string, string> Diagnostics);

/// <summary>
/// Sink abstraction allowing connectors to stream raw documents for persistence.
/// </summary>
public interface IVexRawDocumentSink
{
    ValueTask StoreAsync(VexRawDocument document, CancellationToken cancellationToken);
}

/// <summary>
/// Signature/attestation verification service used while ingesting documents.
/// </summary>
public interface IVexSignatureVerifier
{
    ValueTask<VexSignatureMetadata?> VerifyAsync(VexRawDocument document, CancellationToken cancellationToken);
}

/// <summary>
/// Normalizer router providing format-specific normalization helpers.
/// </summary>
public interface IVexNormalizerRouter
{
    ValueTask<VexClaimBatch> NormalizeAsync(VexRawDocument document, CancellationToken cancellationToken);
}
