import "dotenv/config";
import { knex } from "knex";
import { Model } from "objection";
import { CustomPage } from "../models/CustomPage";
import { ToolPage } from "../models/ToolPage";
import { Language } from "../models/Language";
import knexConfig from "../config/knexfile";
import path from "path";
import fs from "fs";

// Initialize Knex and Objection.js
const environment = process.env.NODE_ENV || "development";
const config = knexConfig[environment];
const db = knex(config);
Model.knex(db);

const isProduction = process.env.NODE_ENV === "production";
const baseDir = path.join(__dirname, "..", "..", "..");

const PROJECT_PUBLIC_CONTENT_PATH = isProduction
  ? path.join(baseDir, "nytsolvers", "dist", "client", "content")
  : path.join(baseDir, "project", "public", "content");

async function generatePages() {
  try {
    console.log("Starting page generation...");

    // Ensure the content directory exists
    if (!fs.existsSync(PROJECT_PUBLIC_CONTENT_PATH)) {
      fs.mkdirSync(PROJECT_PUBLIC_CONTENT_PATH, { recursive: true });
    }

    // Fetch all custom pages
    const customPages = await CustomPage.query().withGraphFetched("language");

    for (const page of customPages) {
      const language = page.language as Language;
      
      // Handle nested slugs
      const slugParts = page.page_slug.split('/');
      const fileName = slugParts.pop() + '.json';
      const dirPath = path.join(PROJECT_PUBLIC_CONTENT_PATH, 'pages', ...slugParts);

      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
      }

      const filePath = path.join(dirPath, fileName);

      const pageData = {
        id: page.id,
        title: page.meta_title,
        description: page.meta_description,
        slug: page.page_slug,
        lang: language.lang_code,
        page_name: page.page_name,
        is_index: page.is_index,
        page_keys: page.page_keys,
        type: "custom",
        page_head_tag: page.page_head_tag,
        before_body_tag: page.before_body_tag,
        canonical: page.canonical,
        noindex: page.noindex ?? false,
        // For custom pages, the file_name is the component name
        template: page.template, 
      };

      fs.writeFileSync(filePath, JSON.stringify(pageData, null, 2));
      console.log(`Generated custom page: ${filePath}`);
    }

    // Fetch all tool pages
    const toolPages = await ToolPage.query().withGraphFetched("language");

    for (const page of toolPages) {
      const language = page.language as Language;
      
      // Handle nested slugs
      const slugParts = page.page_slug.split('/');
      const fileName = slugParts.pop() + '.json';
      const dirPath = path.join(PROJECT_PUBLIC_CONTENT_PATH, 'tools', ...slugParts);

      if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
      }

      const filePath = path.join(dirPath, fileName);

      const pageData = {
        id: page.id,
        title: page.meta_title,
        description: page.meta_description,
        slug: page.page_slug,
        lang: language.lang_code,
        tool_name: page.tool_name,
        is_index: page.is_index,
        page_keys: page.page_keys,
        type: "tool",
        page_head: page.page_head,
        before_body_tag: page.before_body_tag,
        after_body_tag: page.after_body_tag,
        canonical: page.canonical,
        noindex: page.noindex ?? false,
        // For tool pages, the template field holds the component name
        template: page.template,
      };

      fs.writeFileSync(filePath, JSON.stringify(pageData, null, 2));
      console.log(`Generated tool page: ${filePath}`);
    }

    console.log("Page generation completed.");
  } catch (error) {
    console.error("Error during page generation:", error);
    process.exit(1);
  } finally {
    await db.destroy();
  }
}

generatePages();
