/**
 * commands/product-context.mjs — `apt-tools product-context <sub>` (C44).
 *
 * Thin wrapper over `design/product-context.mjs`. Current subcommands:
 *
 *   apt-tools product-context load [project-dir]
 *     → prints the canonical JSON envelope:
 *       {
 *         status: 'ok' | 'error',
 *         command: 'product-context-load',
 *         path: '<abs path to .aperant/product-context.json>',
 *         present: true | false,
 *         source: 'aperant-file' | 'none',
 *         productContext: { ... } | null,
 *         errors: [string, ...],
 *         warnings: [string, ...]
 *       }
 *     Exits 1 when `errors.length > 0`.
 *
 * Future subcommands (`validate`, `show`) layer onto the same dispatch
 * shape. This module is intentionally framework-read-only: the app writes
 * `.aperant/product-context.json` via `saveProjectContextForContext` and
 * the framework consumes it. No LLM calls, no network.
 */

import { resolve as resolvePath } from 'node:path'
import { loadProductContext } from '../design/product-context.mjs'
import { err, exitWith, ok } from '../util/result.mjs'

/**
 * @param {string | undefined} subcommand
 * @param {string[] | undefined} extraArgs  positional + flags after the subcommand
 */
export function cmdProductContext(subcommand, extraArgs) {
	if (!subcommand) {
		return err(
			'apt-tools product-context: missing subcommand. Usage: apt-tools product-context load [project-dir]',
		)
	}

	switch (subcommand) {
		case 'load':
			return cmdLoad(extraArgs ?? [])
		default:
			return err(`apt-tools product-context: unknown subcommand "${subcommand}". Known: load`)
	}
}

/**
 * @param {string[]} args
 */
function cmdLoad(args) {
	// First non-flag positional is the project dir. Default: process.cwd().
	const positional = args.filter((a) => !a.startsWith('--'))
	const projectDirArg = positional[0]
	const projectDir = resolvePath(
		process.cwd(),
		projectDirArg && projectDirArg.length > 0 ? projectDirArg : '.',
	)

	const res = loadProductContext(projectDir)

	const hasErrors = res.errors.length > 0

	const envelope = {
		status: hasErrors ? 'error' : 'ok',
		command: 'product-context-load',
		path: res.path,
		present: res.present,
		source: res.source,
		productContext: res.productContext,
		errors: res.errors,
		warnings: res.warnings,
	}

	return hasErrors ? exitWith(envelope, 1) : ok(envelope)
}
