using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Mindforge.API.Providers;
using Mindforge.API.Repositories;
using Mindforge.API.Services;
using Mindforge.API.Services.Interfaces;

var builder = WebApplication.CreateBuilder(args);

// Ensure environment variables are loaded into IConfiguration
builder.Configuration.AddEnvironmentVariables();

// Add services to the container.
builder.Services.AddControllers();
builder.Logging.AddConsole();
builder.Logging.AddDebug();

// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

// Configure CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// Register HttpClient for providers
builder.Services.AddHttpClient();

// Register Providers
builder.Services.AddScoped<ILlmApiProvider, OpenAIApiProvider>();

// Register Services
builder.Services.AddScoped<IAgentService, AgentService>();
builder.Services.AddScoped<IFileService, FileService>();
builder.Services.AddScoped<IFlashcardService, FlashcardService>();
builder.Services.AddScoped<IFlashcardRepository, FlashcardRepository>();
builder.Services.AddScoped<IGiteaService, GiteaService>();

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    try
    {
        var flashcardRepository = scope.ServiceProvider.GetRequiredService<IFlashcardRepository>();
        await flashcardRepository.EnsureSchemaAsync();
        app.Logger.LogInformation("Flashcard schema checked successfully.");
    }
    catch (Exception ex)
    {
        app.Logger.LogError(ex, "Could not initialize flashcard schema on startup.");
    }
}

app.UseCors("AllowAll");

app.UseMiddleware<Mindforge.API.Middlewares.ExceptionHandlingMiddleware>();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

// Check for env vars
var openAiApiUrl = builder.Configuration["OPENAI_API_URL"];
var openAiToken = builder.Configuration["OPENAI_TOKEN"];
var openAiModel = builder.Configuration["OPENAI_MODEL"];

if (string.IsNullOrEmpty(openAiApiUrl))
    app.Logger.LogWarning("OPENAI_API_URL not found in configuration.");

if (string.IsNullOrEmpty(openAiToken))
    app.Logger.LogWarning("OPENAI_TOKEN not found in configuration.");

if (string.IsNullOrEmpty(openAiModel))
    app.Logger.LogWarning("OPENAI_MODEL not found in configuration.");

var giteaRepoUrl = builder.Configuration["GITEA_REPO_URL"];
var giteaAccessToken = builder.Configuration["GITEA_ACCESS_TOKEN"];

if (string.IsNullOrEmpty(giteaRepoUrl))
    app.Logger.LogWarning("GITEA_REPO_URL not found in configuration. Repository features will not work.");

if (string.IsNullOrEmpty(giteaAccessToken))
    app.Logger.LogWarning("GITEA_ACCESS_TOKEN not found in configuration. Repository features will not work.");

if (string.IsNullOrEmpty(builder.Configuration.GetConnectionString("MindforgeDb")))
    app.Logger.LogWarning("MindforgeDb connection string not found. Falling back to default PostgreSQL connection.");

app.Run();
