import fs from "fs";
import path from "path";
import chalk from "chalk";
import inquirer from "inquirer";
import { configTemplate } from "../configTemplate.js";
import { manifestTemplate } from "../manifestTemplate.js";
import { detectFramework } from "../detectFramework.js";

export const initConfig = async () => {
  console.log(chalk.cyanBright("PWA CLI - Initialization"));
  const framework = await detectFramework();
  console.log(framework);
  if (framework !== "Unknown") return console.log(framework);
  console.log(chalk.red("No framework used"));

  const answers = await inquirer.prompt([
    {
      type: "input",
      name: "configPath",
      message: chalk.yellow("Enter path to generate sw.config.ts:"),
      default: "./sw.config.ts",
    },
    {
      type: "input",
      name: "publicDir",
      message: chalk.yellow("Enter public directory path:"),
      default: "./public",
    },
    {
      type: "input",
      name: "manifestPath",
      message: chalk.yellow("Enter path for manifest.json:"),
      default: (answers: any) => `${answers.publicDir}/manifest.json`,
    },
  ]);

  const configPath = path.resolve(answers.configPath);
  const publicDir = path.resolve(answers.publicDir);
  const manifestPath = path.resolve(answers.manifestPath);

  // Create config file
  if (!fs.existsSync(configPath)) {
    fs.writeFileSync(configPath, configTemplate);
    console.log(chalk.green(`✅ Created ${configPath}`));
  } else {
    console.log(chalk.yellow(`⚠️  ${configPath} already exists, skipping...`));
  }

  // Create public folder if it doesn't exist
  if (!fs.existsSync(publicDir)) {
    fs.mkdirSync(publicDir, { recursive: true });
    console.log(chalk.green(`✅ Created ${publicDir}/`));
  } else {
    console.log(chalk.yellow(`⚠️  ${publicDir}/ already exists, skipping...`));
  }

  // Create manifest.json
  if (!fs.existsSync(manifestPath)) {
    fs.writeFileSync(manifestPath, manifestTemplate);
    console.log(chalk.green(`✅ Created ${manifestPath}`));
  } else {
    console.log(
      chalk.yellow(`⚠️  ${manifestPath} already exists, skipping...`)
    );
  }

  console.log(chalk.cyanBright("\n✅ Initialization complete.\n"));
};
