// Copyright 2019-2026 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Adapted from server/filestore.go (fileStore struct and methods)

using System.Text.Json;
using System.Threading.Channels;
using ZB.MOM.NatsNet.Server.Internal.DataStructures;

namespace ZB.MOM.NatsNet.Server;

/// <summary>
/// File-backed implementation of <see cref="IStreamStore"/>.
/// Stores JetStream messages in per-block files on disk with optional
/// encryption and compression.
/// Mirrors the <c>fileStore</c> struct in filestore.go.
/// </summary>
public sealed class JetStreamFileStore : IStreamStore, IDisposable
{
    // -----------------------------------------------------------------------
    // Fields — mirrors fileStore struct fields
    // -----------------------------------------------------------------------

    private readonly ReaderWriterLockSlim _mu = new(LockRecursionPolicy.NoRecursion);

    // State
    private StreamState _state = new();
    private List<ulong>? _tombs;
    private LostStreamData? _ld;

    // Callbacks
    private StorageUpdateHandler? _scb;
    private StorageRemoveMsgHandler? _rmcb;
    private ProcessJetStreamMsgHandler? _pmsgcb;

    // Age-check timer
    private Timer? _ageChk;
    private bool _ageChkRun;
    private long _ageChkTime;

    // Background sync timer
    private Timer? _syncTmr;

    // Configuration
    private FileStreamInfo _cfg;
    private FileStoreConfig _fcfg;

    // Message block list and index
    private MessageBlock? _lmb;                            // last (active write) block
    private List<MessageBlock> _blks = [];
    private Dictionary<uint, MessageBlock> _bim = [];

    // Per-subject index map
    private SubjectTree<Psi>? _psim;

    // Total subject-list length (sum of subject-string lengths)
    private int _tsl;

    // writeFullState concurrency guard
    private readonly object _wfsmu = new();
    private long _wfsrun;   // Interlocked: is writeFullState running?
    private int _wfsadml;   // Average dmap length (protected by _wfsmu)

    // Quit / load-done channels (Channel<byte> mimics chan struct{})
    private Channel<byte>? _qch;
    private Channel<byte>? _fsld;

    // Consumer list
    private readonly ReaderWriterLockSlim _cmu = new(LockRecursionPolicy.NoRecursion);
    private List<IConsumerStore> _cfs = [];

    // Snapshot-in-progress count
    private int _sips;

    // Dirty-write counter (incremented when writes are pending flush)
    private int _dirty;

    // Lifecycle flags
    private bool _closing;
    private volatile bool _closed;

    // Flush-in-progress flag
    private bool _fip;

    // Whether the store has ever received a message
    private bool _receivedAny;

    // Whether the first sequence has been moved forward
    private bool _firstMoved;

    // Last PurgeEx call time (for throttle logic)
    private DateTime _lpex;

    // In this incremental port stage, file-store logic delegates core stream semantics
    // to the memory store implementation while file-specific APIs are added on top.
    private readonly JetStreamMemStore _memStore;

    // -----------------------------------------------------------------------
    // Constructor
    // -----------------------------------------------------------------------

    /// <summary>
    /// Initialises a file-backed stream store using the supplied file-store
    /// configuration and stream information.
    /// </summary>
    /// <param name="fcfg">File-store configuration (block size, cipher, paths, etc.).</param>
    /// <param name="cfg">Stream metadata (created time and stream config).</param>
    /// <exception cref="ArgumentNullException">
    /// Thrown when <paramref name="fcfg"/> or <paramref name="cfg"/> is null.
    /// </exception>
    public JetStreamFileStore(FileStoreConfig fcfg, FileStreamInfo cfg)
    {
        ArgumentNullException.ThrowIfNull(fcfg);
        ArgumentNullException.ThrowIfNull(cfg);

        _fcfg = fcfg;
        _cfg = cfg;

        // Apply defaults (mirrors newFileStoreWithCreated in filestore.go).
        if (_fcfg.BlockSize == 0)
            _fcfg.BlockSize = FileStoreDefaults.DefaultLargeBlockSize;
        if (_fcfg.CacheExpire == TimeSpan.Zero)
            _fcfg.CacheExpire = FileStoreDefaults.DefaultCacheBufferExpiration;
        if (_fcfg.SubjectStateExpire == TimeSpan.Zero)
            _fcfg.SubjectStateExpire = FileStoreDefaults.DefaultFssExpiration;
        if (_fcfg.SyncInterval == TimeSpan.Zero)
            _fcfg.SyncInterval = FileStoreDefaults.DefaultSyncInterval;

        _psim = new SubjectTree<Psi>();
        _bim = new Dictionary<uint, MessageBlock>();
        _qch = Channel.CreateUnbounded<byte>();
        _fsld = Channel.CreateUnbounded<byte>();

        var memCfg = cfg.Config.Clone();
        memCfg.Storage = StorageType.MemoryStorage;
        _memStore = new JetStreamMemStore(memCfg);
    }

    // -----------------------------------------------------------------------
    // IStreamStore — type / state
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public StorageType Type() => StorageType.FileStorage;

    /// <inheritdoc/>
    public StreamState State()
        => _memStore.State();

    /// <inheritdoc/>
    public void FastState(StreamState state)
        => _memStore.FastState(state);

    // -----------------------------------------------------------------------
    // IStreamStore — callback registration
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public void RegisterStorageUpdates(StorageUpdateHandler cb)
        => _memStore.RegisterStorageUpdates(cb);

    /// <inheritdoc/>
    public void RegisterStorageRemoveMsg(StorageRemoveMsgHandler cb)
        => _memStore.RegisterStorageRemoveMsg(cb);

    /// <inheritdoc/>
    public void RegisterProcessJetStreamMsg(ProcessJetStreamMsgHandler cb)
        => _memStore.RegisterProcessJetStreamMsg(cb);

    // -----------------------------------------------------------------------
    // IStreamStore — lifecycle
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public void Stop()
    {
        _mu.EnterWriteLock();
        try
        {
            if (_closing) return;
            _closing = true;
        }
        finally
        {
            _mu.ExitWriteLock();
        }

        _ageChk?.Dispose();
        _ageChk = null;
        _syncTmr?.Dispose();
        _syncTmr = null;

        _closed = true;
        _memStore.Stop();
    }

    /// <inheritdoc/>
    public void Dispose() => Stop();

    // -----------------------------------------------------------------------
    // IStreamStore — store / load (all stubs)
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public (ulong Seq, long Ts) StoreMsg(string subject, byte[]? hdr, byte[]? msg, long ttl)
        => _memStore.StoreMsg(subject, hdr, msg, ttl);

    /// <inheritdoc/>
    public void StoreRawMsg(string subject, byte[]? hdr, byte[]? msg, ulong seq, long ts, long ttl, bool discardNewCheck)
        => _memStore.StoreRawMsg(subject, hdr, msg, seq, ts, ttl, discardNewCheck);

    /// <inheritdoc/>
    public (ulong Seq, Exception? Error) SkipMsg(ulong seq)
        => _memStore.SkipMsg(seq);

    /// <inheritdoc/>
    public void SkipMsgs(ulong seq, ulong num)
        => _memStore.SkipMsgs(seq, num);

    /// <inheritdoc/>
    public void FlushAllPending()
        => _memStore.FlushAllPending();

    /// <inheritdoc/>
    public StoreMsg? LoadMsg(ulong seq, StoreMsg? sm)
        => _memStore.LoadMsg(seq, sm);

    /// <inheritdoc/>
    public (StoreMsg? Sm, ulong Skip) LoadNextMsg(string filter, bool wc, ulong start, StoreMsg? smp)
        => _memStore.LoadNextMsg(filter, wc, start, smp);

    /// <inheritdoc/>
    public (StoreMsg? Sm, ulong Skip) LoadNextMsgMulti(object? sl, ulong start, StoreMsg? smp)
        => _memStore.LoadNextMsgMulti(sl, start, smp);

    /// <inheritdoc/>
    public StoreMsg? LoadLastMsg(string subject, StoreMsg? sm)
        => _memStore.LoadLastMsg(subject, sm);

    /// <inheritdoc/>
    public (StoreMsg? Sm, Exception? Error) LoadPrevMsg(ulong start, StoreMsg? smp)
        => _memStore.LoadPrevMsg(start, smp);

    /// <inheritdoc/>
    public (StoreMsg? Sm, ulong Skip, Exception? Error) LoadPrevMsgMulti(object? sl, ulong start, StoreMsg? smp)
        => _memStore.LoadPrevMsgMulti(sl, start, smp);

    /// <inheritdoc/>
    public (bool Removed, Exception? Error) RemoveMsg(ulong seq)
        => _memStore.RemoveMsg(seq);

    /// <inheritdoc/>
    public (bool Removed, Exception? Error) EraseMsg(ulong seq)
        => _memStore.EraseMsg(seq);

    /// <inheritdoc/>
    public (ulong Purged, Exception? Error) Purge()
        => _memStore.Purge();

    /// <inheritdoc/>
    public (ulong Purged, Exception? Error) PurgeEx(string subject, ulong seq, ulong keep)
        => _memStore.PurgeEx(subject, seq, keep);

    /// <inheritdoc/>
    public (ulong Purged, Exception? Error) Compact(ulong seq)
        => _memStore.Compact(seq);

    /// <inheritdoc/>
    public void Truncate(ulong seq)
        => _memStore.Truncate(seq);

    // -----------------------------------------------------------------------
    // IStreamStore — query methods (all stubs)
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public ulong GetSeqFromTime(DateTime t)
        => _memStore.GetSeqFromTime(t);

    /// <inheritdoc/>
    public SimpleState FilteredState(ulong seq, string subject)
        => _memStore.FilteredState(seq, subject);

    /// <inheritdoc/>
    public Dictionary<string, SimpleState> SubjectsState(string filterSubject)
        => _memStore.SubjectsState(filterSubject);

    /// <inheritdoc/>
    public Dictionary<string, ulong> SubjectsTotals(string filterSubject)
        => _memStore.SubjectsTotals(filterSubject);

    /// <inheritdoc/>
    public (ulong[] Seqs, Exception? Error) AllLastSeqs()
        => _memStore.AllLastSeqs();

    /// <inheritdoc/>
    public (ulong[] Seqs, Exception? Error) MultiLastSeqs(string[] filters, ulong maxSeq, int maxAllowed)
        => _memStore.MultiLastSeqs(filters, maxSeq, maxAllowed);

    /// <inheritdoc/>
    public (string Subject, Exception? Error) SubjectForSeq(ulong seq)
        => _memStore.SubjectForSeq(seq);

    /// <inheritdoc/>
    public (ulong Total, ulong ValidThrough, Exception? Error) NumPending(ulong sseq, string filter, bool lastPerSubject)
        => _memStore.NumPending(sseq, filter, lastPerSubject);

    /// <inheritdoc/>
    public (ulong Total, ulong ValidThrough, Exception? Error) NumPendingMulti(ulong sseq, object? sl, bool lastPerSubject)
        => _memStore.NumPendingMulti(sseq, sl, lastPerSubject);

    // -----------------------------------------------------------------------
    // IStreamStore — stream state encoding (stubs)
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public (byte[] Enc, Exception? Error) EncodedStreamState(ulong failed)
        => _memStore.EncodedStreamState(failed);

    /// <inheritdoc/>
    public void SyncDeleted(DeleteBlocks dbs)
        => _memStore.SyncDeleted(dbs);

    // -----------------------------------------------------------------------
    // IStreamStore — config / admin (stubs)
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public void UpdateConfig(StreamConfig cfg)
    {
        _cfg.Config = cfg.Clone();
        _memStore.UpdateConfig(cfg);
    }

    /// <inheritdoc/>
    public void Delete(bool inline)
        => _memStore.Delete(inline);

    /// <inheritdoc/>
    public void ResetState()
        => _memStore.ResetState();

    // -----------------------------------------------------------------------
    // IStreamStore — consumer management (stubs)
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public IConsumerStore ConsumerStore(string name, DateTime created, ConsumerConfig cfg)
    {
        var cfi = new FileConsumerInfo
        {
            Name = name,
            Created = created,
            Config = cfg,
        };
        var odir = Path.Combine(_fcfg.StoreDir, FileStoreDefaults.ConsumerDir, name);
        Directory.CreateDirectory(odir);
        var cs = new ConsumerFileStore(this, cfi, name, odir);
        AddConsumer(cs);
        return cs;
    }

    /// <inheritdoc/>
    public void AddConsumer(IConsumerStore o)
    {
        _cmu.EnterWriteLock();
        try
        {
            _cfs.Add(o);
            _memStore.AddConsumer(o);
        }
        finally { _cmu.ExitWriteLock(); }
    }

    /// <inheritdoc/>
    public void RemoveConsumer(IConsumerStore o)
    {
        _cmu.EnterWriteLock();
        try
        {
            _cfs.Remove(o);
            _memStore.RemoveConsumer(o);
        }
        finally { _cmu.ExitWriteLock(); }
    }

    // -----------------------------------------------------------------------
    // IStreamStore — snapshot / utilization (stubs)
    // -----------------------------------------------------------------------

    /// <inheritdoc/>
    public (SnapshotResult? Result, Exception? Error) Snapshot(TimeSpan deadline, bool includeConsumers, bool checkMsgs)
    {
        var state = _memStore.State();
        var payload = JsonSerializer.SerializeToUtf8Bytes(state);
        var reader = new MemoryStream(payload, writable: false);
        return (new SnapshotResult { Reader = reader, State = state }, null);
    }

    /// <inheritdoc/>
    public (ulong Total, ulong Reported, Exception? Error) Utilization()
        => _memStore.Utilization();
}
