#!/usr/bin/env node

import inquirer from "inquirer";
import fs from "fs-extra";
import path from "path";
import chalk from "chalk";
import ora from "ora";
import { fileURLToPath } from "url";
import packageJson from "./package.json" with { type: "json" };

// Cross-platform __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const run = async () => {
  try {
    console.clear();

    const templatesDir = path.join(__dirname, "templates");

    // Verify templates folder exists
    if (!fs.existsSync(templatesDir)) {
      console.error(
        chalk.red(`
❌ Templates folder not found.

Expected:
${templatesDir}

Make sure the templates folder is included in the published package.
`)
      );
      process.exit(1);
    }

    const templateChoices = fs
      .readdirSync(templatesDir)
      .filter((item) =>
        fs.statSync(path.join(templatesDir, item)).isDirectory()
      )
      .sort();

    console.log(
      chalk.blue(`
╔══════════════════════════════════════════════════════╗
║                       Aviation               ║
║                 Version ${packageJson.version.padEnd(25)}║
╚══════════════════════════════════════════════════════╝
`)
    );

    console.log(
      chalk.green(`
Generate complete MERN projects instantly.
`)
    );

    console.log(
      chalk.yellow(`
Available Templates: ${templateChoices.length}
`)
    );

    const args = process.argv.slice(2);
    let projectName = args[0];

    if (!projectName) {
      const res = await inquirer.prompt([
        {
          type: "input",
          name: "name",
          message: "Project name:",
          default: "my-app",
          validate: (input) =>
            input.trim() !== "" || "Project name cannot be empty",
        },
      ]);

      projectName = res.name.trim();
    }

    const projectPath = path.join(process.cwd(), projectName);

    if (await fs.pathExists(projectPath)) {
      console.log(
        chalk.red(
          `\n❌ A folder named "${projectName}" already exists.\n`
        )
      );
      process.exit(1);
    }

    const { template } = await inquirer.prompt([
      {
        type: "list",
        name: "template",
        message: "Choose a template:",
        choices: templateChoices,
        pageSize: 15,
      },
    ]);

    const spinner = ora("Creating project...").start();

    const templatePath = path.join(templatesDir, template);

    if (!fs.existsSync(templatePath)) {
      spinner.fail("Template not found");
      process.exit(1);
    }

    await fs.copy(templatePath, projectPath);

    spinner.succeed("Project created successfully!");

    console.log(
      chalk.green(`
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ PROJECT CREATED SUCCESSFULLY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
`)
    );

    console.log(chalk.cyan(`📂 Project : ${projectName}`));
    console.log(chalk.cyan(`📦 Template: ${template}`));
    console.log(chalk.cyan(`📍 Location: ${projectPath}`));

    console.log(
      chalk.yellow(`
Next Steps:
`)
    );

    console.log(chalk.white(`cd "${projectName}"`));
    console.log(
      chalk.green(`
Backend:
`)
    );

    console.log(chalk.white(`cd backend`));
    console.log(chalk.white(`npm install`));
    console.log(chalk.white(`npm run dev`));

    console.log(
      chalk.green(`
Frontend:
`)
    );

    console.log(chalk.white(`cd frontend`));
    console.log(chalk.white(`npm install`));
    console.log(chalk.white(`npm run dev`));

    console.log(
      chalk.magenta(`
🚀 Happy Coding!
`)
    );
  } catch (error) {
    console.error(
      chalk.red(`
❌ Error

${error.message}
`)
    );

    process.exit(1);
  }
};

run();