import fs, { globSync } from "node:fs";
import path from "node:path";
import { parseTestCasesFromDoc } from "../commands/parse-doc-test-cases";
import { APP_PATHS } from "../commands/lib/paths";
import { parseResolverDoc } from "./parse-resolver-doc";
import { renderStub } from "./stub-templates";
import { scaffoldAppBoilerplate } from "./scaffold";

export function runGenerateAppCode(appPath: string): number {
  const appName = path.basename(appPath);
  scaffoldAppBoilerplate(appPath, appName);

  generateResolverStubs(appPath, appName);
  generateStoryTestStubs(appPath, appName);

  return 0;
}

function generateResolverStubs(appPath: string, appName: string): void {
  const docsDir = path.join(appPath, "docs", "resolver");
  if (!fs.existsSync(docsDir)) return;

  const mdFiles = fs.readdirSync(docsDir).filter((f) => f.endsWith(".md"));
  if (mdFiles.length === 0) return;

  const resolverDir = path.join(appPath, "backend", "src", "resolvers");
  fs.mkdirSync(resolverDir, { recursive: true });
  let generated = 0;

  for (const file of mdFiles) {
    const content = fs.readFileSync(path.join(docsDir, file), "utf-8");
    const fileName = path.basename(file, ".md");
    const doc = parseResolverDoc(fileName, content);

    const implFile = path.join(resolverDir, `${doc.resolverName}.ts`);
    if (!fs.existsSync(implFile)) {
      fs.writeFileSync(implFile, renderStub("resolver", doc.resolverName));
      console.log(`  scaffolded ${path.relative(appPath, implFile)}`);
      generated++;
    }
  }

  if (generated > 0) {
    console.log(`Scaffolded ${generated} resolver(s) for ${appName}`);
  }
}

function generateStoryTestStubs(appPath: string, appName: string): void {
  const storyPattern = path.join(appPath, "docs/business-flow/*/story/*.md");
  const storyDocs = globSync(storyPattern);
  let generated = 0;

  for (const storyDocPath of storyDocs) {
    const content = fs.readFileSync(storyDocPath, "utf-8");
    const testCases = parseTestCasesFromDoc(content);
    if (testCases.length === 0) continue;

    const regex = /\/docs\/business-flow\/([^/]+)\/story\/([^/]+)\.md$/;
    const match = regex.exec(storyDocPath);
    if (!match) continue;
    const [, flow, storyName] = match;

    const testDir = path.join(appPath, APP_PATHS.tests.stories, flow);
    const testFile = path.join(testDir, `${storyName}.test.ts`);
    if (fs.existsSync(testFile)) continue;

    fs.mkdirSync(testDir, { recursive: true });
    fs.writeFileSync(testFile, renderStub("storyTest", storyName, testCases));
    console.log(`  scaffolded ${path.relative(appPath, testFile)}`);
    generated++;
  }

  if (generated > 0) {
    console.log(`Scaffolded ${generated} story test(s) for ${appName}`);
  }
}
