import path from "node:path";
import fs from "node:fs/promises";
import { parse, stringify } from "yaml";

//#region src/coderclaw/project-context.ts
const CODERCLAW_DIR = ".coderClaw";
const CONTEXT_FILE = "context.yaml";
const ARCHITECTURE_FILE = "architecture.md";
const RULES_FILE = "rules.yaml";
const AGENTS_DIR = "agents";
const SKILLS_DIR = "skills";
const MEMORY_DIR = "memory";
const SESSIONS_DIR = "sessions";
/**
* Resolve the .coderClaw directory for a project
*/
function resolveCoderClawDir(projectRoot) {
	const root = path.join(projectRoot, CODERCLAW_DIR);
	return {
		root,
		contextPath: path.join(root, CONTEXT_FILE),
		architecturePath: path.join(root, ARCHITECTURE_FILE),
		rulesPath: path.join(root, RULES_FILE),
		agentsDir: path.join(root, AGENTS_DIR),
		skillsDir: path.join(root, SKILLS_DIR),
		memoryDir: path.join(root, MEMORY_DIR),
		sessionsDir: path.join(root, SESSIONS_DIR)
	};
}
/**
* Check if a project has been initialized with coderClaw
*/
async function isCoderClawProject(projectRoot) {
	const dir = resolveCoderClawDir(projectRoot);
	try {
		return (await fs.stat(dir.root)).isDirectory();
	} catch {
		return false;
	}
}
/**
* Initialize a new coderClaw project directory
*/
async function initializeCoderClawProject(projectRoot, context) {
	const dir = resolveCoderClawDir(projectRoot);
	await fs.mkdir(dir.root, { recursive: true });
	await fs.mkdir(dir.agentsDir, { recursive: true });
	await fs.mkdir(dir.skillsDir, { recursive: true });
	await fs.mkdir(dir.memoryDir, { recursive: true });
	await fs.mkdir(dir.sessionsDir, { recursive: true });
	const defaultContext = {
		version: 1,
		projectName: context?.projectName || path.basename(projectRoot),
		description: context?.description || "A coderClaw-enabled project",
		rootPath: projectRoot,
		languages: context?.languages || [],
		frameworks: context?.frameworks || [],
		architecture: context?.architecture || {
			style: "unknown",
			layers: [],
			patterns: []
		},
		buildSystem: context?.buildSystem,
		testFramework: context?.testFramework,
		lintingTools: context?.lintingTools || [],
		dependencies: context?.dependencies || {
			production: {},
			development: {}
		},
		customRules: context?.customRules || [],
		metadata: context?.metadata || {},
		...context?.llm ? { llm: context.llm } : {},
		...context?.clawLink ? { clawLink: context.clawLink } : {}
	};
	await fs.writeFile(dir.contextPath, stringify(defaultContext), "utf-8");
	await fs.writeFile(dir.architecturePath, `# Architecture

## Overview

This document describes the architectural design and patterns used in this project.

## Components

### Core Modules

(To be documented)

## Design Patterns

(To be documented)

## Data Flow

(To be documented)

## Dependencies

(To be documented)
`, "utf-8");
	await fs.writeFile(dir.rulesPath, stringify({
		version: 1,
		codeStyle: {
			indentation: "spaces",
			indentSize: 2,
			lineLength: 100,
			namingConventions: {}
		},
		testing: {
			required: true,
			coverage: 80,
			frameworks: []
		},
		documentation: {
			required: true,
			format: "markdown",
			location: "docs/"
		},
		git: {
			branchNaming: "feature/*, fix/*, docs/*",
			commitFormat: "conventional",
			requireReview: true
		},
		constraints: [],
		customRules: []
	}), "utf-8");
	await fs.writeFile(path.join(dir.root, "README.md"), `# .coderClaw Directory

This directory contains project-specific context and configuration for coderClaw.

## Structure

- \`context.yaml\` - Project metadata, languages, frameworks, dependencies
- \`architecture.md\` - Architectural documentation and design patterns
- \`rules.yaml\` - Coding standards, testing requirements, git conventions
- \`agents/\` - Custom agent role definitions
- \`skills/\` - Project-specific skills
- \`memory/\` - Project knowledge base and semantic indices
- \`sessions/\` - Session handoff documents (resume any session instantly)

## Usage

coderClaw agents automatically load context from this directory when working on the project.
`, "utf-8");
}
/**
* Update specific fields in context.yaml without overwriting unrelated data.
*/
async function updateProjectContextFields(projectRoot, updates) {
	const dir = resolveCoderClawDir(projectRoot);
	const updated = {
		...parse(await fs.readFile(dir.contextPath, "utf-8")),
		...updates
	};
	await fs.writeFile(dir.contextPath, stringify(updated), "utf-8");
}
/**
* Load project context from .coderClaw directory
*/
async function loadProjectContext(projectRoot) {
	const dir = resolveCoderClawDir(projectRoot);
	try {
		return parse(await fs.readFile(dir.contextPath, "utf-8"));
	} catch {
		return null;
	}
}
/**
* Load project rules from .coderClaw directory
*/
async function loadProjectRules(projectRoot) {
	const dir = resolveCoderClawDir(projectRoot);
	try {
		return parse(await fs.readFile(dir.rulesPath, "utf-8"));
	} catch {
		return null;
	}
}
/**
* Load project architecture documentation
*/
async function loadProjectArchitecture(projectRoot) {
	const dir = resolveCoderClawDir(projectRoot);
	try {
		return await fs.readFile(dir.architecturePath, "utf-8");
	} catch {
		return null;
	}
}
/**
* Load custom agent roles from .coderClaw/agents/
*/
async function loadCustomAgentRoles(projectRoot) {
	const dir = resolveCoderClawDir(projectRoot);
	const roles = [];
	try {
		const files = await fs.readdir(dir.agentsDir);
		for (const file of files) if (file.endsWith(".yaml") || file.endsWith(".yml")) {
			const role = parse(await fs.readFile(path.join(dir.agentsDir, file), "utf-8"));
			roles.push(role);
		}
	} catch {}
	return roles;
}

//#endregion
export { loadProjectContext as a, loadProjectArchitecture as i, isCoderClawProject as n, loadProjectRules as o, loadCustomAgentRoles as r, updateProjectContextFields as s, initializeCoderClawProject as t };