using Kompas.Mcp.Core.Documents;
using Kompas.Mcp.Core.Drawings;
using Kompas.Mcp.Core.Modeling;

namespace Kompas.Mcp.Tests.Integration;

/// <summary>Интеграция: стандартные ассоциативные виды чертежа (API7 IViews.AddStandartViews).</summary>
[Trait("Category", "Integration")]
[Collection(KompasCollection.Name)]
public sealed class DrawingTests : IntegrationTestBase
{
    private readonly DocumentService _docs;
    private readonly PartModeler _modeler;
    private readonly DrawingService _drawing;

    public DrawingTests(KompasFixture fx) : base(fx)
    {
        _docs = new DocumentService(fx.Session, fx.Dispatcher);
        _modeler = new PartModeler(fx.Session, fx.Dispatcher);
        _drawing = new DrawingService(fx.Session, fx.Dispatcher);
    }

    private async Task<string> BuildAndSaveBoxAsync()
    {
        var path = TestPaths.NewFile(".m3d");
        await _docs.CreateAsync(KompasDocumentType.Part);
        try
        {
            var s = await _modeler.OpenSketchAsync(BasePlane.XOY);
            await _modeler.AddRectangleAsync(s, 0, 0, 40, 30);
            await _modeler.CloseSketchAsync(s);
            await _modeler.ExtrudeAsync(s, depth: 20);
            await _modeler.RebuildAsync();
            await _docs.SaveAsAsync(path);
        }
        finally { await _docs.CloseAsync(save: false); }

        Assert.True(File.Exists(path), $"Файл детали не сохранён: {path}");
        Assert.True(new FileInfo(path).Length > 0, "Файл детали пуст.");
        return path;
    }

    [Fact]
    public async Task Creates_three_standard_views_on_drawing()
    {
        var partFile = await BuildAndSaveBoxAsync();

        await _docs.CreateAsync(KompasDocumentType.Drawing);
        try
        {
            var r = await _drawing.CreateStandardViewsAsync(partFile, scale: 1.0, x: 100, y: 150);

            // Создано ровно 3 вида (спереди/сверху/слева); всего на чертеже +3 к системному виду.
            Assert.Equal(3, r.Created);
            Assert.True(r.Total >= 4, $"Ожидалось ≥4 видов всего (системный + 3), получено {r.Total}.");
        }
        finally { await _docs.CloseAsync(save: false); }
    }

    [Fact]
    public async Task Rejects_non_drawing_document()
    {
        // Активный документ — деталь (не чертёж): понятная ошибка.
        var partFile = await BuildAndSaveBoxAsync();

        await _docs.CreateAsync(KompasDocumentType.Part);
        try
        {
            await Assert.ThrowsAsync<InvalidOperationException>(
                () => _drawing.CreateStandardViewsAsync(partFile, scale: 1.0, x: 100, y: 150));
        }
        finally { await _docs.CloseAsync(save: false); }
    }

    [Fact]
    public async Task Missing_model_file_throws()
    {
        var missing = Path.Combine(TestPaths.Scratch, $"no_such_{Guid.NewGuid():N}.m3d");

        await _docs.CreateAsync(KompasDocumentType.Drawing);
        try
        {
            await Assert.ThrowsAsync<FileNotFoundException>(
                () => _drawing.CreateStandardViewsAsync(missing, scale: 1.0, x: 100, y: 150));
        }
        finally { await _docs.CloseAsync(save: false); }
    }
}
