using YTExtractor;
using Serilog;
using Serilog.Sinks.InfluxDB;
using YTExtractor.Data;

// App configuration and endpoints
var builder = WebApplication.CreateBuilder(args);

var environment = builder.Environment.EnvironmentName;

Log.Logger = new LoggerConfiguration()
   .WriteTo.InfluxDB(
       address: "http://192.168.0.76",
       dbName: "telegraf",
       source: "YTExtractor-{environment}")
   .Enrich.WithProperty("Environment", environment)
   .CreateLogger();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<MongoDBConnector>();

var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();


app.MapPost("/api/video-info", async (VideoRequest request, MongoDBConnector mongo) =>
{
    try
    {
        if (!YoutubeService.IsValidYouTubeUrl(request.Url))
            return Results.BadRequest("Invalid YouTube URL");

        var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
        Directory.CreateDirectory(tempDir);

        try
        {
            Log.Information($"Obtendo dados do video: {request.Url}");

            var videoExists = await mongo.GetVideoByUrl(request.Url);
            if (videoExists != null)
            {
                return Results.Ok(new VideoInfo(
                    videoExists.Url,
                    videoExists.Titulo,
                    videoExists.ThumbnailUrl,
                    videoExists.TranscText
                ));
            }

            var info = await YoutubeService.GetVideoInfo(request.Url, tempDir);
            var subtitles = await YoutubeService.GetSubtitles(request.Url, request.Language, tempDir);

            await mongo.InsertVideo(new VideoData
            {
                Url = request.Url,
                Titulo = info.Title,
                ThumbnailUrl = info.ThumbnailUrl,
                TranscText = subtitles
            });

            Log.Information($"Dados de video obtidos: {request.Url}");
            return Results.Ok(new VideoInfo(
                request.Url,
                info.Title,
                info.ThumbnailUrl,
                subtitles
            ));
        }
        finally
        {
            if (Directory.Exists(tempDir))
                Directory.Delete(tempDir, true);
        }
    }
    catch (Exception ex)
    {
        Log.Error(ex, "Failed to get video info");
        return Results.Problem(ex.Message);
    }
})
.WithName("GetVideoInfo")
.WithOpenApi();

app.Run();