using RolemasterDb.ImportTool.Parsing;

namespace RolemasterDb.ImportTool;

public sealed class XmlCriticalSourceExtractor(PdfXmlExtractor pdfXmlExtractor) : ICriticalSourceExtractor
{
    public async Task ExtractAsync(string pdfPath, ImportArtifactPaths artifactPaths, CancellationToken cancellationToken = default) =>
        await pdfXmlExtractor.ExtractAsync(pdfPath, artifactPaths.XmlPath, cancellationToken);

    public async Task<ExtractedCriticalSource> LoadAsync(
        string pdfPath,
        ImportArtifactPaths artifactPaths,
        CancellationToken cancellationToken = default)
    {
        if (!File.Exists(artifactPaths.XmlPath))
        {
            throw new FileNotFoundException($"Missing XML artifact: {artifactPaths.XmlPath}", artifactPaths.XmlPath);
        }

        var xmlContent = await File.ReadAllTextAsync(artifactPaths.XmlPath, cancellationToken);
        return new ExtractedCriticalSource(
            "xml",
            "Imported from PDF XML extraction.",
            SourceRenderProfile.XmlAligned(),
            CriticalTableParserSupport.LoadPageGeometries(xmlContent),
            CriticalTableParserSupport.LoadFragments(xmlContent));
    }
}
