import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import { execFile, ExecFileException } from 'child_process';
import { getMkdocsPath } from './environment';
import { generateMkdocsConfig, restoreOriginalConfig } from './config-generator';
import { resolvePorts } from './port-manager';

export async function buildSite(
  workspaceDir: string,
  output: vscode.OutputChannel
): Promise<void> {
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mkdocs-wysiwyg-build-'));

  try {
    const ports = await resolvePorts();

    output.appendLine('Generating mkdocs.yml for build...');
    generateMkdocsConfig({
      workspaceDir,
      tmpDir,
      websocketPort: ports.websocketPort,
      apiPort: 0,
      useUserTheme: false,
      autoGenerated: false,
    });

    const mkdocsPath = getMkdocsPath();
    if (!fs.existsSync(mkdocsPath)) {
      throw new Error(`mkdocs not found at ${mkdocsPath}. Run "MkDocs WYSIWYG: Upgrade Environment" first.`);
    }

    output.appendLine('Running mkdocs build...');

    await new Promise<void>((resolve, reject) => {
      execFile(
        mkdocsPath,
        ['build', '-f', path.join(workspaceDir, 'mkdocs.yml')],
        {
          cwd: workspaceDir,
          env: { ...process.env, TMPDIR: tmpDir, TMP_DIR: tmpDir },
        },
        (err: ExecFileException | null, stdout: string, stderr: string) => {
          if (stdout) { output.append(stdout); }
          if (stderr) { output.append(stderr); }
          if (err) {
            reject(new Error(`mkdocs build failed: ${err.message}`));
          } else {
            resolve();
          }
        }
      );
    });

    output.appendLine('Build complete.');
  } finally {
    restoreOriginalConfig(workspaceDir, tmpDir);
    try {
      fs.rmSync(tmpDir, { recursive: true, force: true });
    } catch {
      // best-effort cleanup
    }
  }
}
