/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 *
 * Fractal‑Syntax‑Forge Engine
 * Engineered by James Burvel O'Callaghan III for Citibank Demo Business Inc.
 *
 * Mission: Birth “**FGL – Fractal Genesis Language**”, a meta‑programming tongue for
 * engineering reality layers, holographic simulations, and 13‑D hyperframes.
 *
 * Paste into any TS‑aware bundler, supply your Gemini‑compatible key via
 * `process.env.API_KEY`, open in‑browser, and watch constructs manifest.
 */

import { marked } from 'marked';
import OpenAI, {
  type ClientOptions,
  type ChatCompletionMessageParam,
} from 'openai';

// ──────────────────────────────────────────────────────────────
// ENV + OpenAI init
// ──────────────────────────────────────────────────────────────

const API_KEY = process.env.API_KEY;
if (!API_KEY) throw new Error('Missing API_KEY env var');

const openai = new OpenAI({
  apiKey: API_KEY,
  baseURL: 'https://generativelanguage.googleapis.com/v1beta/openai/',
  dangerouslyAllowBrowser: true,
} as ClientOptions);

// ──────────────────────────────────────────────────────────────
// Fractal console
// ──────────────────────────────────────────────────────────────

async function consoleRender(...md: string[]): Promise<void> {
  const el = document.createElement('section');
  Object.assign(el.style, {
    padding: '1.6rem',
    background: 'radial-gradient(circle at top left,#0f172a 0%,#1e293b 40%,#020617 100%)',
    border: '1px solid #6366f1',
    borderRadius: '20px',
    color: '#f1f5f9',
    fontFamily: 'Fira Code, monospace',
    margin: '1.5rem 0',
    lineHeight: '1.6',
    boxShadow: '0 0 30px rgba(99,102,241,0.25)',
  } as Partial<CSSStyleDeclaration>);

  el.innerHTML = (await Promise.all(md.map((m) => marked.parse(m)))).join('');
  document.body.appendChild(el);
}

// ──────────────────────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────────────────────

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

async function chat(messages: ChatCompletionMessageParam[]): Promise<string> {
  const rsp = await openai.chat.completions.create({ model: 'gemini-2.0-flash', messages });
  const out = rsp.choices?.[0]?.message?.content ?? '';
  if (!out) throw new Error('LLM yielded empty');
  return out;
}

// ──────────────────────────────────────────────────────────────
// Prompts for FGL
// ──────────────────────────────────────────────────────────────

const SYS_PROMPT =
  'You are FGL‑Core, a cosmic compiler forged by James Burvel O’Callaghan III. Your task: crystallise Fractal Genesis Language, a DSL for designing holographic realities and 13‑dimensional hyperframes. Emit concise Markdown with syntax blocks, metaphysical notes, and practical simulation hooks.';

const CONSTRUCT_PROMPT = (n: number) => `### Construct ${n}
Define Construct ${n} of FGL.
Include:
1. **Syntax pattern** – formal grammar.
2. **Sample \`fgl\` code**.
3. **Underlying metaphysics** – e.g., tesseract mapping, state‑vector displacement.
4. **Applied use‑case** – rendering cosmic scenes, morphing temporal logic, or tuning quantum chips.`;

// ──────────────────────────────────────────────────────────────
// Loop control
// ──────────────────────────────────────────────────────────────

let stop = false;
(window as any).stopLoop = () => (stop = true);

(async () => {
  try {
    await consoleRender('# 🌌 FGL Genesis Console', 'Spinning reality fibres…');

    const MAX = 40; // language constructs
    for (let c = 1; c <= MAX; c++) {
      if (stop) break;

      let backoff = 2500;
      while (true) {
        try {
          const def = await chat([
            { role: 'system', content: SYS_PROMPT },
            { role: 'user', content: CONSTRUCT_PROMPT(c) },
          ]);
          await consoleRender(`---\n\n## 🌀 Construct ${c}`, def);
          break;
        } catch (e) {
          console.error(`Construct ${c} failed`, e);
          await sleep(backoff);
          backoff = Math.min(backoff * 2, 60000);
        }
      }

      await sleep(4000);
    }

    await consoleRender('✨ **FGL genesis complete. Engage the matrix.**');
  } catch (fatal) {
    await consoleRender('💣 Fatal:', String(fatal));
  }
})();
