namespace OCES.Resonance.Core;

/// <summary>
/// 音频库管理服务，协调扫描、读取和入库的完整流程
/// </summary>
public class AudioLibraryService
{
    private readonly AudioFileScanner _scanner;
    private readonly AudioMetadataReader _metadataReader;

    public AudioLibraryService()
    {
        _scanner = new AudioFileScanner();
        _metadataReader = new AudioMetadataReader();
    }

    /// <summary>
    /// 扫描目录并将结果添加到数据库
    /// </summary>
    /// <param name="directoryPath">要扫描的目录路径</param>
    /// <param name="databaseName">数据库名称（不含扩展名）</param>
    /// <param name="skipExisting">是否跳过已存在的文件</param>
    /// <returns>扫描结果统计</returns>
    public async Task<ScanResult> ScanAndImportToLibrary(
        string directoryPath, 
        string databaseName = "default",
        bool skipExisting = true)
    {
        var result = new ScanResult
        {
            TotalFiles = 0,
            SuccessCount = 0,
            SkipCount = 0,
            ErrorCount = 0,
            Errors = new List<string>()
        };

        // 初始化数据库
        Database.InitializeDatabase();

        // 扫描所有音频文件
        var audioFiles = _scanner.ScanDirectory(directoryPath).ToList();
        result.TotalFiles = audioFiles.Count;

        if (audioFiles.Count == 0)
        {
            return result;
        }

        var metadataList = new List<AudioFileMeta>();

        // 读取每个文件的元数据
        foreach (var filePath in audioFiles)
        {
            try
            {
                // 计算 MD5 用于查重
                var md5 = CalculateMd5ForFile(filePath);

                // 检查是否已存在
                if (skipExisting && Database.EntryExists(md5, filePath))
                {
                    result.SkipCount++;
                    continue;
                }

                // 读取元数据
                var metadata = _metadataReader.ReadMetadata(filePath);
                metadataList.Add(metadata);
                result.SuccessCount++;
            }
            catch (Exception ex)
            {
                result.ErrorCount++;
                result.Errors.Add($"读取失败 {filePath}: {ex.Message}");
            }
        }

        // 批量入库
        if (metadataList.Count > 0)
        {
            try
            {
                Database.AddEntries(metadataList);
            }
            catch (Exception ex)
            {
                result.Errors.Add($"批量入库失败：{ex.Message}");
                throw;
            }
        }

        return await Task.FromResult(result);
    }

    /// <summary>
    /// 计算文件 MD5（用于查重，不创建完整 AudioFileMeta 对象）
    /// </summary>
    private static string CalculateMd5ForFile(string filePath)
    {
        using var md5 = System.Security.Cryptography.MD5.Create();
        using var stream = File.OpenRead(filePath);
        var hash = md5.ComputeHash(stream);
        return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
    }
}

/// <summary>
/// 扫描结果统计
/// </summary>
public class ScanResult
{
    /// <summary>扫描到的文件总数</summary>
    public int TotalFiles { get; set; }

    /// <summary>成功入库的文件数</summary>
    public int SuccessCount { get; set; }

    /// <summary>跳过的文件数（已存在）</summary>
    public int SkipCount { get; set; }

    /// <summary>读取失败的文件数</summary>
    public int ErrorCount { get; set; }

    /// <summary>错误详情列表</summary>
    public List<string> Errors { get; set; } = new();

    /// <summary>
    /// 获取人类可读的统计报告
    /// </summary>
    public string GetSummary()
    {
        return $"扫描完成：共 {TotalFiles} 个文件，成功 {SuccessCount} 个，跳过 {SkipCount} 个，失败 {ErrorCount} 个";
    }
}
