import { DEFAULT_THEME_DOCUMENT } from '../logic/theme-defaults.logic';
import { THEME_LAYOUT_CONTAINERS, THEME_REGISTRY } from '../logic/theme-registry.logic';
import {
  THEME_ANIMATION_FIELDS,
  THEME_ELEMENT_STYLE_FIELDS,
  createAnimationStarterDefinition
} from '../logic/theme-schema.logic';

function formatExample(example: string | number): string {
  return typeof example === 'number' ? `${example}` : JSON.stringify(example);
}

function getLayoutKeysForContainer(containerKey: string): string[] {
  return THEME_REGISTRY.filter((entry) => entry.container === containerKey && entry.layoutEditable).map((entry) => entry.key);
}

function describeCapabilities(entry: (typeof THEME_REGISTRY)[number]): string {
  const capabilities = [
    entry.layoutEditable ? 'layout' : null,
    entry.supportsTextOverride ? 'textOverride' : null,
    entry.supportsLink ? 'link' : null,
    entry.supportsIcon ? 'icon' : null
  ].filter((value): value is string => value !== null);

  return capabilities.length > 0 ? capabilities.join(', ') : 'visual style overrides only';
}

function describeLayoutContainer(container: (typeof THEME_LAYOUT_CONTAINERS)[number]): string {
  const layoutKeys = getLayoutKeysForContainer(container.key);

  return [
    `- ${container.key}: ${container.columns} columns x ${container.rows} rows.`,
    container.description,
    `Layout keys: ${layoutKeys.join(', ')}.`
  ].join(' ');
}

function describeThemeEntry(entry: (typeof THEME_REGISTRY)[number]): string {
  const container = entry.container ?? 'none';

  return [
    `- ${entry.key}: ${entry.label}.`,
    `Category=${entry.category}.`,
    `Container=${container}.`,
    entry.description,
    `Supported extras: ${describeCapabilities(entry)}.`
  ].join(' ');
}

const colorTokenKeys = Object.keys(DEFAULT_THEME_DOCUMENT.tokens.colors);
const radiusTokenKeys = Object.keys(DEFAULT_THEME_DOCUMENT.tokens.radii);
const effectTokenKeys = Object.keys(DEFAULT_THEME_DOCUMENT.tokens.effects);
const layoutEditableKeys = THEME_REGISTRY.filter((entry) => entry.layoutEditable).map((entry) => entry.key);
const layoutContainerKeys = THEME_LAYOUT_CONTAINERS.map((container) => container.key);
const layoutContainerUnion = layoutContainerKeys.map((key) => `"${key}"`).join(' | ');
const guideTemplateDocument = {
  meta: {
    name: 'Theme Name',
    version: '1.0.0',
    description: 'Short mood and material direction.'
  },
  css: '',
  tokens: {
    colors: {
      background: '224 28% 7%',
      foreground: '210 40% 96%',
      primary: '193 95% 68%',
      panelBackground: '224 24% 11%',
      titleBarBackground: '226 34% 7%'
    },
    spacing: {},
    radii: {
      radius: '0.875rem',
      surface: '1.35rem'
    },
    effects: {
      glassBlur: 'blur(18px) saturate(135%)'
    }
  },
  layout: {
    chatRoomMainPanel: {
      container: 'roomLayout',
      grid: {
        x: 4,
        y: 0,
        w: 12,
        h: 12
      }
    }
  },
  elements: {
    titleBar: {
      backgroundColor: 'hsl(var(--title-bar-background) / 0.82)',
      color: 'hsl(var(--foreground))',
      border: '1px solid hsl(var(--border) / 0.72)',
      backdropFilter: 'var(--theme-effect-glass-blur)'
    },
    chatRoomMainPanel: {
      backgroundColor: 'hsl(var(--panel-background) / 0.82)',
      backgroundImage: '/assets/themes/paper-noise.png',
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      borderRadius: 'var(--theme-radius-surface)',
      boxShadow: 'var(--theme-effect-panel-shadow)'
    }
  },
  animations: {
    'theme-fade-in': createAnimationStarterDefinition()
  }
};

export const THEME_LLM_GUIDE = [
  'TOJU THEME CREATION SHEET FOR LLMS',
  '',
  'Goal',
  '- Produce one valid JSON theme document for Toju Theme Studio.',
  '- Return JSON only when asked to generate a theme. Do not wrap the result in Markdown fences or add commentary.',
  '',
  'Core rules',
  '- Supported top-level keys are meta, css, tokens, layout, elements, and animations. Omit sections that do not need overrides.',
  '- Use strict JSON with double-quoted keys, no comments, and no trailing commas.',
  '- Omitted layout keys use the app default placement. Omitted element keys apply no Theme Studio visual override.',
  '- Do not invent new top-level sections, layout containers, or element style properties.',
  '- links must be absolute http or https URLs.',
  '- animationClass must be a safe CSS class token and should match an entry in animations or an existing class already shipped by the app.',
  '- css is optional raw CSS applied after the JSON theme is active. Keep selectors scoped to app/theme surfaces when possible.',
  '- layout.grid values must be integers. x and y are zero-based. w and h must be greater than 0.',
  '- opacity must be a number between 0 and 1.',
  '',
  'Theme creation workflow',
  '- 1. Set meta.name, meta.version, and an optional meta.description.',
  '- 2. Define the palette and tokens first. Prefer token-driven colors instead of hard-coded values in every element.',
  '- 3. Move only layout-editable surfaces in layout.',
  '- 4. Add visual overrides in elements using the supported style fields below.',
  '- 5. Add animations only when an element actually references them with animationClass.',
  '',
  'Token rules',
  '- tokens.colors entries become CSS variables like --background or --surface-highlight-alt.',
  '- Color token values should usually be raw HSL channels such as "224 28% 7%". The shell wraps many built-in color tokens with hsl(var(--token)).',
  '- You may add extra color tokens if you also reference them with CSS variables in element overrides.',
  '- elements.<key>.backgroundImage accepts a CSS background-image value, a local image path, or an http/https image URL.',
  '- Use backgroundSize and backgroundPosition with backgroundImage when the image needs cover/center behavior.',
  '- tokens.spacing entries become --theme-spacing-<kebab-case-key>.',
  '- tokens.radii.radius maps to --radius. Other radius keys become --theme-radius-<kebab-case-key>.',
  '- tokens.effects entries become --theme-effect-<kebab-case-key>.',
  `- Built-in shell color tokens: ${colorTokenKeys.join(', ')}.`,
  `- Built-in shell radius tokens: ${radiusTokenKeys.join(', ')}.`,
  `- Built-in shell effect tokens: ${effectTokenKeys.join(', ')}.`,
  '',
  'Top-level schema reference',
  '- meta: { name: string, version: string, description?: string }',
  '- css?: string',
  '- tokens: { colors: Record<string, string>, spacing: Record<string, string>, radii: Record<string, string>, effects: Record<string, string> }',
  `- layout: Record<string, { container: ${layoutContainerUnion}, grid: { x: number, y: number, w: number, h: number } }>`,
  '- elements: Record<string, ThemeElementStyles>',
  '- animations: Record<string, { duration?, easing?, delay?, iterationCount?, fillMode?, direction?, keyframes? }>',
  '',
  'Layout containers',
  ...THEME_LAYOUT_CONTAINERS.map((container) => describeLayoutContainer(container)),
  `- Only these keys should normally appear in layout: ${layoutEditableKeys.join(', ')}.`,
  '',
  'Registered theme element keys',
  ...THEME_REGISTRY.map((entry) => describeThemeEntry(entry)),
  '',
  'Supported element style fields',
  ...THEME_ELEMENT_STYLE_FIELDS.map((field) => {
    return `- ${field.key}: ${field.description} Example: ${formatExample(field.example)}.`;
  }),
  '',
  'Supported animation fields',
  ...THEME_ANIMATION_FIELDS.map((field) => {
    return `- ${field.key}: ${field.description} Example: ${formatExample(field.example)}.`;
  }),
  '',
  'Minimal valid starting point',
  JSON.stringify(guideTemplateDocument, null, 2),
  '',
  'Output checklist',
  '- Return one JSON object only.',
  '- Prefer token references like hsl(var(--foreground)) and var(--theme-effect-glass-blur) inside element overrides.',
  '- Keep layout edits plausible for the declared container grid size.',
  '- If a field is unsupported, omit it instead of guessing.',
  '- If a section does not need changes, leave it empty rather than filling it with noise.'
].join('\n');
