/**
 * commands/team.mjs — team subcommand (C29).
 */

import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { getGitIdentity } from '../git/identity.mjs'
import { teamSync } from '../team/team.mjs'
import { withFileLock } from '../util/fs-lock.mjs'
import { atomicWriteJson } from '../util/io.mjs'
import { err, ok } from '../util/result.mjs'

/**
 * team subcommand: init | status | list | disable | sync
 */
export function cmdTeam(subcommand, projectDir, extraArgs) {
	if (!subcommand) return err('Usage: apt-tools team <init|status|list|disable|sync> <project-dir>')
	if (!projectDir) return err('Usage: apt-tools team ' + subcommand + ' <project-dir>')

	const targetDir = resolve(projectDir)
	const teamPath = join(targetDir, '.aperant', 'team.json')

	switch (subcommand) {
		case 'init': {
			mkdirSync(join(targetDir, '.aperant'), { recursive: true })

			const identity = getGitIdentity(targetDir)
			const now = new Date().toISOString()

			let team = { version: 1, enabled: true, members: {} }
			if (existsSync(teamPath)) {
				try {
					team = JSON.parse(readFileSync(teamPath, 'utf-8'))
				} catch {
					/* reset on corruption */
				}
				team.enabled = true
				if (!team.members) team.members = {}
			}

			if (identity) {
				team.members[identity.email] = team.members[identity.email] || {
					name: identity.name,
					email: identity.email,
					joined_at: now,
				}
				team.members[identity.email].name = identity.name
			}

			writeFileSync(teamPath, JSON.stringify(team, null, 2) + '\n', 'utf-8')

			// C34: the legacy active.json seed was removed. The per-agent
			// team-status/ directory is lazily created by the coordination
			// store on first upsert.

			return ok({
				status: 'ok',
				command: 'team-init',
				team,
				current_user: identity,
			})
		}

		case 'status': {
			if (!existsSync(teamPath)) {
				return ok({ status: 'ok', command: 'team-status', enabled: false })
			}
			const team = JSON.parse(readFileSync(teamPath, 'utf-8'))
			const identity = getGitIdentity(targetDir)
			return ok({
				status: 'ok',
				command: 'team-status',
				enabled: team.enabled === true,
				member_count: Object.keys(team.members || {}).length,
				current_user: identity,
				is_registered: identity ? !!team.members?.[identity.email] : false,
			})
		}

		case 'list': {
			if (!existsSync(teamPath)) {
				return ok({ status: 'ok', command: 'team-list', members: [] })
			}
			const team = JSON.parse(readFileSync(teamPath, 'utf-8'))
			return ok({
				status: 'ok',
				command: 'team-list',
				members: Object.values(team.members || {}),
			})
		}

		case 'disable': {
			if (!existsSync(teamPath)) return err('No team.json found')
			withFileLock(teamPath, () => {
				const team = JSON.parse(readFileSync(teamPath, 'utf-8'))
				team.enabled = false
				atomicWriteJson(teamPath, team)
			})
			return ok({ status: 'ok', command: 'team-disable' })
		}

		case 'sync': {
			// Parse flags: --push (bool), --message <msg>
			let push = false
			let message = null
			for (let i = 0; i < extraArgs.length; i++) {
				if (extraArgs[i] === '--push') {
					push = true
				} else if (extraArgs[i] === '--message' && i + 1 < extraArgs.length) {
					message = extraArgs[i + 1]
					i++
				}
			}
			const result = teamSync(targetDir, { push, message })
			return ok({ command: 'team-sync', ...result })
		}

		default:
			return err(
				`Unknown team subcommand: ${subcommand}. Expected: init, status, list, disable, sync`,
			)
	}
}
