using AuthorBuddy.Web.Data;
using LiteDB;

namespace AuthorBuddy.Web.Services;

public class FileScannerService : IFileScannerService
{
    private readonly IOllamaService _ollama;
    private readonly ILiteDatabase _db;

    public FileScannerService(IOllamaService ollama, ILiteDatabase db)
    {
        _ollama = ollama;
        _db = db;
    }

    public async Task ScanProjectFolderAsync(int projectId, string rootPath, IProgress<string> progress)
    {
        var files = Directory.GetFiles(rootPath, "*.md", SearchOption.AllDirectories)
                             .Where(f => f.Contains("00_Drafts") || f.Contains("01_Fakten"));

        foreach (var file in files)
        {
            var fileInfo = new FileInfo(file);
            bool needsUpdate = CheckIfUpdateRequired(projectId, file, fileInfo.LastWriteTimeUtc);

            if (needsUpdate)
            {
                progress?.Report($"Verarbeite: {fileInfo.Name}...");
                await ProcessFile(projectId, file, fileInfo.LastWriteTimeUtc);
            }
        }
        progress?.Report("Scan abgeschlossen.");
    }

    private bool CheckIfUpdateRequired(int projectId, string file, DateTime lastWriteTimeUtc)
    {
        var col = _db.GetCollection<DocumentMetaEntity>("documentMeta");
        var meta = col.FindOne(m => m.ProjectId == projectId && m.FilePath == file);
        if (meta == null) return true;
        return meta.LastModified < lastWriteTimeUtc;
    }

    private async Task<bool> ProcessFile(int projectId, string path, DateTime lastModified)
    {
        string content = await File.ReadAllTextAsync(path);

        try
        {
            var col = _db.GetCollection<DocumentMetaEntity>("documentMeta");
            var existing = col.FindOne(m => m.ProjectId == projectId && m.FilePath == path);

            if (existing != null)
            {
                existing.LastModified = lastModified;
                col.Update(existing);
            }
            else
            {
                col.Insert(new DocumentMetaEntity
                {
                    ProjectId = projectId,
                    FilePath = path,
                    LastModified = lastModified,
                    FileType = ".md"
                });
            }

            return true;
        }
        catch
        {
            return false;
        }
    }
}
