/**
 * commands/init-state.mjs — init-state command (C29).
 */

import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { err, ok } from '../util/result.mjs'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

export function cmdInitState(projectDir, args) {
	if (!projectDir) return err('Usage: apt-tools init-state <project-dir> --config <json>')
	const targetDir = resolve(projectDir)
	const aperantDir = join(targetDir, '.aperant')

	// Parse --config flag (JSON string)
	const configIdx = args.indexOf('--config')
	if (configIdx < 0) return err('Required: --config <json-string>')
	const configStr = args.slice(configIdx + 1).join(' ')
	let userConfig
	try {
		userConfig = JSON.parse(configStr)
	} catch (e) {
		return err('Invalid JSON for --config: ' + e.message)
	}

	// Read template config, merge with user overrides
	const templatePath = resolve(__dirname, '..', '..', '..', 'templates', 'config.json')
	const template = JSON.parse(readFileSync(templatePath, 'utf-8'))
	const mergedConfig = { ...template, ...userConfig }

	// Deep-merge nested objects (autonomy, qa, risk_map, etc.)
	for (const key of Object.keys(userConfig)) {
		if (
			userConfig[key] &&
			typeof userConfig[key] === 'object' &&
			!Array.isArray(userConfig[key]) &&
			template[key]
		) {
			mergedConfig[key] = { ...template[key], ...userConfig[key] }
		}
	}

	// Ensure .aperant/ exists with all subdirs (C36: context → context/installed + context/notes, drop plans)
	for (const subdir of [
		'context/installed',
		'context/notes',
		'standards',
		'features',
		'locks',
		'events',
		'proof',
	]) {
		mkdirSync(join(aperantDir, subdir), { recursive: true })
	}

	// Write config
	writeFileSync(
		join(aperantDir, 'config.json'),
		JSON.stringify(mergedConfig, null, 2) + '\n',
		'utf-8',
	)

	// Write state
	const statePath = join(aperantDir, 'state.json')
	if (!existsSync(statePath)) {
		const stateTemplate = resolve(__dirname, '..', '..', '..', 'templates', 'state.json')
		const state = JSON.parse(readFileSync(stateTemplate, 'utf-8'))
		state.initialized_at = new Date().toISOString()
		state.last_activity = new Date().toISOString()
		writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n', 'utf-8')
	}

	// Append gitignore rules if not already present
	const gitignorePath = join(targetDir, '.gitignore')
	const gitignoreTemplatePath = resolve(
		__dirname,
		'..',
		'..',
		'..',
		'templates',
		'gitignore-aperant',
	)
	if (existsSync(gitignoreTemplatePath)) {
		const rules = readFileSync(gitignoreTemplatePath, 'utf-8')
		const existing = existsSync(gitignorePath) ? readFileSync(gitignorePath, 'utf-8') : ''
		if (!existing.includes('.aperant/locks/')) {
			const separator =
				existing.length > 0 && !existing.endsWith('\n') ? '\n\n' : existing.length > 0 ? '\n' : ''
			writeFileSync(gitignorePath, existing + separator + rules + '\n', 'utf-8')
		}
	}

	return ok({
		status: 'ok',
		command: 'init-state',
		projectDir: targetDir,
		config_written: join(aperantDir, 'config.json'),
		state_written: statePath,
		directories_created: [
			'context/installed',
			'context/notes',
			'standards',
			'features',
			'locks',
			'events',
			'proof',
		],
	})
}
