/** GOA V1.0 — LLM architect via Hyper-Loop (JSON-only output). */

import { buildGoaExecutionPayload, parseGoaPayloadJson } from '@/lib/goa-architect';
import { hyperloopProcess } from '@/lib/vigthoria-services';
import type { GoaArchitectInput, GoaExecutionPayload } from '@/types/goa-orchestrator';

export const GOA_MASTER_INSTRUCTION = `# ROLE: VIGTHORIA GOA CORE ORCHESTRATOR

## 1. ABSOLUTE INPUT PARSING BOUNDARY
Categorize the workspace:
- IS_GREENFIELD: new feature/project matching template database
- IS_BROWNFIELD: modifying/fixing existing repository

## 2. METADATA-DRIVEN ANALYSIS
Use ONLY the metadata tree provided. Never invent file paths.

## 3. STRUCTURAL OUTPUT SPECIFICATION
Output MUST be a single parsable JSON GoaExecutionPayload object only.
No markdown. No prose outside JSON.

Schema:
{
  "workspace_type": "GREENFIELD | BROWNFIELD",
  "analysis": {
    "detected_framework": "string",
    "target_files": ["path"]
  },
  "instructions": [
    {
      "sequence": 1,
      "engine": "CLI_TEMPLATE | AST_TRANSFORMER | STABILIZATION",
      "command": "EXECUTE_TEMPLATE_INJECTION | EXECUTE_AST_MUTATION | RUN_STABILIZATION_CHECK",
      "payload": {
        "template_id": "string_or_null",
        "file_path": "string",
        "operation": "ADD_IMPORT | REPLACE_BODY | INJECT_WRAPPER | APPEND_PROPERTY | INSERT_BEFORE",
        "target_node": "string",
        "variables": {},
        "code_payload": "string"
      }
    }
  ]
}`;

export async function buildGoaPayloadWithPlanner(
  input: GoaArchitectInput,
  hyperloopUrl: string,
  token: string | null,
): Promise<GoaExecutionPayload> {
  const fallback = buildGoaExecutionPayload(input);
  if (!token) return fallback;

  const metaJson = JSON.stringify(input.astMetadata ?? {}, null, 2).slice(0, 4000);
  const prompt = [
    GOA_MASTER_INSTRUCTION,
    `USER PROMPT:\n${input.userPrompt}`,
    `IS_EXISTING_PROJECT: ${input.isExistingProject}`,
    `TEMPLATE_MATCH: ${input.templateMatch?.id ?? 'none'}`,
    `AST_METADATA_TREE:\n${metaJson}`,
    `FALLBACK_PAYLOAD (use as base, refine only):\n${JSON.stringify(fallback)}`,
  ].join('\n\n');

  try {
    const raw = await hyperloopProcess(hyperloopUrl, token, prompt, input.workspaceRoot);
    const text =
      typeof raw.result === 'string'
        ? raw.result
        : typeof raw.output === 'string'
          ? raw.output
          : JSON.stringify(raw.result ?? raw);
    const match = text.match(/\{[\s\S]*"workspace_type"[\s\S]*"instructions"[\s\S]*\}/);
    if (!match) return fallback;
    const parsed = parseGoaPayloadJson(match[0]);
    return parsed ?? fallback;
  } catch {
    return fallback;
  }
}
