using LiquidCode.Tester.Worker.Models;

namespace LiquidCode.Tester.Worker.Services;

public class PythonCompilationService : ICompilationService
{
    private readonly ILogger<PythonCompilationService> _logger;
    private readonly IConfiguration _configuration;

    public PythonCompilationService(ILogger<PythonCompilationService> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    public async Task<CompilationResult> CompileAsync(string sourceCode, string workingDirectory, string? version = null)
    {
        var sourceFilePath = Path.Combine(workingDirectory, "solution.py");

        _logger.LogInformation("Preparing Python code in {WorkingDirectory} with version {Version}", workingDirectory, version ?? "latest");

        try
        {
            await File.WriteAllTextAsync(sourceFilePath, sourceCode);

            // Resolve version-specific executable (for execution service)
            var executable = ResolveVersion(version);

            _logger.LogDebug("Using Python executable: {Executable}", executable);
            _logger.LogInformation("Python code prepared successfully (no compilation needed)");

            return new CompilationResult
            {
                Success = true,
                ExecutablePath = sourceFilePath,
                CompilerOutput = $"Python is an interpreted language - no compilation needed (using {executable})"
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error preparing Python code");
            return new CompilationResult
            {
                Success = false,
                ErrorMessage = $"Error preparing code: {ex.Message}"
            };
        }
    }

    private string ResolveVersion(string? version)
    {
        // If version is null or "latest", use default configuration
        if (string.IsNullOrEmpty(version) || version.Equals("latest", StringComparison.OrdinalIgnoreCase))
        {
            var executable = _configuration["Python:Executable"] ?? "python3";
            return executable;
        }

        // Try to find version-specific configuration
        var versionKey = $"Python:Versions:{version}";
        var versionExecutable = _configuration[$"{versionKey}:Executable"];

        if (!string.IsNullOrEmpty(versionExecutable))
        {
            _logger.LogInformation("Using Python version {Version} configuration", version);
            return versionExecutable;
        }

        // Version not found, use default and log warning
        _logger.LogWarning("Python version {Version} not found in configuration, using default", version);
        var defaultExecutable = _configuration["Python:Executable"] ?? "python3";
        return defaultExecutable;
    }
}
