using System.Text.Json;
using Microsoft.Extensions.Logging;

namespace MMail.Client.Services;

/// <summary>
/// 统计本实例在磁盘上占了多少地方,结果写进数据库。
///
/// 一开始是在请求里现算的,结果设置页那个数字一直停在「统计中」:遍历成千上万个
/// .eml 和附件要几分钟,HTTP 请求等不起,用户看到的就只能是「还没好」。
/// 改成这里在后台慢慢地算,算完存库,页面只读库里那一个数——
/// 差半小时的精度换一个立刻能看到的数字,对这个用途是划算的。
/// </summary>
public sealed class StorageUsageService : BackgroundService
{
    /// <summary>存进 Setting 表的位置。不新建表是为了不必为三个数据库各写一份迁移。</summary>
    public const string Category = "System";
    public const string Key = "StorageUsage";

    private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);

    private readonly AppSettingsService _settings;
    private readonly MailStore _store;
    private readonly ILogger<StorageUsageService> _logger;

    // 页面触发的统计和定时那趟可能撞在一起,门闩保证同一时刻只跑一趟。
    // 遍历磁盘本身很慢,跑两遍纯属浪费。
    private readonly SemaphoreSlim _gate = new(1, 1);

    public StorageUsageService(
        AppSettingsService settings, MailStore store, ILogger<StorageUsageService> logger)
    {
        _settings = settings;
        _store = store;
        _logger = logger;
    }

    /// <summary>上一次统计的结果。还没统计过(或存的值坏了)返回 null。</summary>
    public async Task<StorageUsage?> ReadAsync(CancellationToken ct)
    {
        var json = await _settings.GetAsync(Category, Key, ct);
        if (string.IsNullOrWhiteSpace(json)) return null;

        try
        {
            return JsonSerializer.Deserialize<StorageUsage>(json);
        }
        catch (JsonException ex)
        {
            // 值坏了就当没统计过,下一趟统计会把它覆盖掉
            _logger.LogWarning(ex, "库里的磁盘占用记录无法解析,当作未统计。");
            return null;
        }
    }

    /// <summary>
    /// 要求立刻统计一次。已经在统计中就什么都不做——那一趟的结果一样新。
    /// 这是给「还没有任何统计结果」时补一趟用的,调用方不必等它完成。
    /// </summary>
    public async Task RefreshAsync(CancellationToken ct = default)
    {
        if (!await _gate.WaitAsync(0, ct)) return;

        try
        {
            await MeasureAsync(ct);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "统计磁盘占用失败。");
        }
        finally
        {
            _gate.Release();
        }
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("磁盘占用统计服务启动,间隔 {Minutes} 分钟", Interval.TotalMinutes);

        // 开机先让一让:迁移、首次同步都在这一刻抢资源,不差这几秒
        try
        {
            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
        }
        catch (OperationCanceledException)
        {
            return;
        }

        using var timer = new PeriodicTimer(Interval);

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await _gate.WaitAsync(stoppingToken);
                try
                {
                    await MeasureAsync(stoppingToken);
                }
                finally
                {
                    _gate.Release();
                }
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "本轮磁盘占用统计失败");
            }

            try
            {
                await timer.WaitForNextTickAsync(stoppingToken);
            }
            catch (OperationCanceledException)
            {
                break;
            }
        }

        _logger.LogInformation("磁盘占用统计服务已停止");
    }

    private async Task MeasureAsync(CancellationToken ct)
    {
        // 邮件与附件单列:它们是占地方的大头,也是唯一能靠删邮件回收的部分。
        // 其余(数据库、Data Protection 密钥)归在一起,再拆下去没有意义。
        //
        // 仓库目录可能被数据目录包住,也可能不(Storage:Root 能配到别处),
        // 所以统计「其余」时要跳开仓库子树,否则同一批文件会被算两遍。
        var mailBytes = Measure(_store.Root);
        var otherBytes = Measure(PathHelper.DataDirectory, _store.Root);

        var usage = new StorageUsage(mailBytes, otherBytes, mailBytes + otherBytes, DateTime.UtcNow);
        await _settings.SetAsync(Category, Key, JsonSerializer.Serialize(usage), false, ct);

        _logger.LogInformation(
            "磁盘占用统计完成:合计 {Total} 字节(邮件与附件 {Mail},其余 {Other})",
            usage.TotalBytes, usage.MailBytes, usage.OtherBytes);
    }

    /// <summary>
    /// 递归累加目录里所有文件的长度。
    /// 用显式栈而不是 AllDirectories:后者遇到读不了的目录会整个中断,而且没法跳过子树。
    /// </summary>
    private static long Measure(string root, string? skip = null)
    {
        if (!Directory.Exists(root)) return 0;

        var skipPath = string.IsNullOrWhiteSpace(skip) ? null : Path.GetFullPath(skip);
        var pending = new Stack<string>();
        pending.Push(Path.GetFullPath(root));

        long total = 0;

        while (pending.Count > 0)
        {
            var dir = pending.Pop();

            // 目录正被同步任务改着是常态。这里只是给用户看一个数,少算几个文件
            // 不影响结论;抛出去反而让整个统计作废。
            try
            {
                foreach (var file in new DirectoryInfo(dir).EnumerateFiles())
                {
                    try { total += file.Length; }
                    catch (IOException) { }
                    catch (UnauthorizedAccessException) { }
                }

                foreach (var sub in Directory.EnumerateDirectories(dir))
                {
                    if (skipPath is null || !IsSameOrUnder(skipPath, sub)) pending.Push(sub);
                }
            }
            catch (IOException) { }
            catch (UnauthorizedAccessException) { }
        }

        return total;
    }

    private static bool IsSameOrUnder(string parent, string candidate)
    {
        var full = Path.GetFullPath(candidate);

        return string.Equals(full, parent, StringComparison.Ordinal)
               || full.StartsWith(parent + Path.DirectorySeparatorChar, StringComparison.Ordinal);
    }
}

public sealed record StorageUsage(
    long MailBytes,
    long OtherBytes,
    long TotalBytes,
    DateTime MeasuredAt);