using System.Runtime.InteropServices;

namespace EpsonPrintService;

public static class ConfigurationPaths
{
    private const string LinuxConfigDir = "/root/epsonprintservice";
    private const string LocalConfigFileName = "config.txt";

    public static string GetConfigPath()
    {
        // Check for explicit override via environment variable
        var envPath = Environment.GetEnvironmentVariable("EPSON_CONFIG_PATH");
        if (!string.IsNullOrEmpty(envPath))
            return envPath;

        // Windows: always use local config.json
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            return LocalConfigFileName;
        }

        // Linux: use persistent system directory
        var persistentPath = Path.Combine(LinuxConfigDir, LocalConfigFileName);

        // If persistent config exists, use it
        if (File.Exists(persistentPath))
        {
            return persistentPath;
        }

        // If only local config exists, migrate it to persistent location
        if (File.Exists(LocalConfigFileName))
        {
            MigrateConfig(LocalConfigFileName, persistentPath);
            return persistentPath;
        }

        // Default to persistent path (will fail if doesn't exist, which is expected)
        return persistentPath;
    }

    private static void MigrateConfig(string sourcePath, string destinationPath)
    {
        try
        {
            var destDir = Path.GetDirectoryName(destinationPath);
            if (!string.IsNullOrEmpty(destDir) && !Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }

            File.Copy(sourcePath, destinationPath, overwrite: false);
            Console.WriteLine($"Migrated configuration from {sourcePath} to {destinationPath}");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine($"Warning: Cannot migrate config to {destinationPath} (permission denied). Using local config.");
            // Fall back to local config if we can't write to system directory
        }
        catch (IOException ex) when (ex.Message.Contains("already exists"))
        {
            // File was created by another process, that's fine
        }
    }

    public static string GetConfigDirectory()
    {
        var configPath = GetConfigPath();
        return Path.GetDirectoryName(configPath) ?? ".";
    }
}
