import * as path from "path";
import { fileURLToPath } from 'url';
import { promises as fs } from "fs";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

async function loadPackageJson() {
  const packageJsonPath = path.join(__dirname, 'package.json');
  const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');
  return JSON.parse(packageJsonContent);
}

interface ManifestIcon {
  src: string;
  sizes: string;
  type: string;
  purpose?: string;
}

interface ShareTarget {
  action: string;
  method: "POST";
  enctype: string;
  params: {
    files: Array<{
      name: string;
      accept: string[];
    }>;
  };
}

interface PWAConfig {
  registerType: string;
  strategies: string;
  srcDir: string;
  filename: string;
  manifest: {
    name: string;
    short_name: string;
    theme_color: string;
    background_color: string;
    icons: ManifestIcon[];
    share_target: ShareTarget;
  };
}

interface AppConfig {
  pwaConfig: PWAConfig;
  aliasConfig: {
    [key: string]: string;
  };
}

export async function loadAppConfig(): Promise<AppConfig> {
  const packageJson = await loadPackageJson();
  const appName = process.env.TIME_SAFARI_APP_TITLE || packageJson.name;

  return {
    pwaConfig: {
      registerType: "autoUpdate",
      strategies: "injectManifest",
      srcDir: ".",
      filename: "sw_scripts-combined.js",
      manifest: {
        name: appName,
        short_name: appName,
        theme_color: "#4a90e2",
        background_color: "#ffffff",
        icons: [
          {
            src: "./img/icons/android-chrome-192x192.png",
            sizes: "192x192",
            type: "image/png",
          },
          {
            src: "./img/icons/android-chrome-512x512.png",
            sizes: "512x512",
            type: "image/png",
          },
          {
            src: "./img/icons/android-chrome-maskable-192x192.png",
            sizes: "192x192",
            type: "image/png",
            purpose: "maskable",
          },
          {
            src: "./img/icons/android-chrome-maskable-512x512.png",
            sizes: "512x512",
            type: "image/png",
            purpose: "maskable",
          },
        ],
        share_target: {
          action: "/share-target",
          method: "POST",
          enctype: "multipart/form-data",
          params: {
            files: [
              {
                name: "photo",
                accept: ["image/*"],
              },
            ],
          },
        },
      },
    },
    aliasConfig: {
      "@": path.resolve(__dirname, "src"),
      buffer: path.resolve(__dirname, "node_modules", "buffer"),
      "dexie-export-import/dist/import":
        "dexie-export-import/dist/import/index.js",
    },
  };
}