// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
// SPDX-FileCopyrightText: Petr Baudis <pasky@ucw.cz>
//
// SPDX-License-Identifier: MIT

import {
	getAgentDir,
	SettingsManager,
	type ExtensionAPI,
	type ExtensionContext,
	type SessionEntry,
} from "@earendil-works/pi-coding-agent";
import * as path from "node:path";

/**
 * Model override sources for handoff extraction calls. Use provider/modelId
 * values (e.g. "anthropic/claude-haiku-4-5"). Precedence is:
 * --handoff-model, PI_HANDOFF_MODEL, user settings handoffModel, session model.
 */
const HANDOFF_MODEL_FLAG = "handoff-model";
const HANDOFF_MODEL_ENV = "PI_HANDOFF_MODEL";
const HANDOFF_MODEL_SETTING = "handoffModel";

export function registerHandoffModelFlag(pi: ExtensionAPI): void {
	pi.registerFlag(HANDOFF_MODEL_FLAG, {
		description: "Model for handoff extraction as provider/modelId",
		type: "string",
	});
}

function nonEmptyString(value: string | undefined): string | undefined {
	const trimmed = value?.trim();
	return trimmed ? trimmed : undefined;
}

function stringProperty(source: object, key: string): string | undefined {
	const descriptor = Object.getOwnPropertyDescriptor(source, key);
	if (!descriptor || !("value" in descriptor)) return undefined;
	return typeof descriptor.value === "string" ? nonEmptyString(descriptor.value) : undefined;
}

function userSettingsHandoffModel(cwd: string): string | undefined {
	const settingsManager = SettingsManager.create(cwd, getAgentDir());
	return stringProperty(settingsManager.getGlobalSettings(), HANDOFF_MODEL_SETTING);
}

function configuredHandoffModel(pi: ExtensionAPI, ctx: { cwd: string }): string | undefined {
	const flagValue = pi.getFlag(HANDOFF_MODEL_FLAG);
	const flagModel = typeof flagValue === "string" ? nonEmptyString(flagValue) : undefined;
	return flagModel ?? nonEmptyString(process.env[HANDOFF_MODEL_ENV]) ?? userSettingsHandoffModel(ctx.cwd);
}

function parseModelSpec(spec: string): { provider: string; modelId: string } | undefined {
	const slashIdx = spec.indexOf("/");
	if (slashIdx <= 0 || slashIdx === spec.length - 1) return undefined;
	return {
		provider: spec.slice(0, slashIdx),
		modelId: spec.slice(slashIdx + 1),
	};
}

/**
 * Build a candidate file set from two sources:
 *   1. Primary: actual tool calls (read, write, edit, create) in the session
 *   2. Secondary: file-like patterns in the conversation text (catches files
 *      that were discussed but never opened)
 */
export function extractCandidateFiles(entries: SessionEntry[], conversationText: string): Set<string> {
	const files = new Set<string>();
	const fileToolNames = new Set(["read", "write", "edit", "create"]);

	// Primary: files from actual tool calls
	for (const entry of entries) {
		if (entry.type !== "message") continue;
		const msg = entry.message;
		if (msg.role !== "assistant") continue;

		for (const block of msg.content) {
			if (typeof block !== "object" || block === null || block.type !== "toolCall") continue;
			if (!fileToolNames.has(block.name)) continue;

			const args = block.arguments as Record<string, unknown>;
			const filePath =
				typeof args.path === "string" ? args.path : typeof args.file === "string" ? args.file : undefined;
			if (!filePath) continue;
			if (filePath.endsWith("/SKILL.md")) continue;

			files.add(filePath);
		}
	}

	// Secondary: file-like patterns from conversation text.
	// Trailing lookahead so the boundary isn't consumed — otherwise adjacent
	// files separated by a single space (e.g. "file1.txt file2.txt") get skipped.
	const filePattern = /(?:^|\s)([a-zA-Z0-9._\-/]+\.[a-zA-Z0-9]+)(?=\s|$|[,;:)])/gm;
	for (const match of conversationText.matchAll(filePattern)) {
		const candidate = match[1];
		if (candidate && !candidate.startsWith(".") && candidate.length > 2) {
			files.add(candidate);
		}
	}

	return files;
}

/**
 * Extract skill names that were actually loaded during the conversation.
 * Looks for read() tool calls targeting SKILL.md files and derives the
 * skill name from the parent directory (the convention for pi skills).
 */
export function extractLoadedSkills(entries: SessionEntry[]): string[] {
	const skills = new Set<string>();
	for (const entry of entries) {
		if (entry.type !== "message") continue;
		const msg = entry.message;
		if (msg.role !== "assistant") continue;

		for (const block of msg.content) {
			if (typeof block !== "object" || block === null || block.type !== "toolCall") continue;

			// read() calls where the path ends in SKILL.md
			if (block.name !== "read") continue;
			const args = block.arguments as Record<string, unknown>;
			const filePath = typeof args.path === "string" ? args.path : undefined;
			if (!filePath?.endsWith("/SKILL.md")) continue;

			// Skill name is the parent directory name:
			//   .../skills/backing-up-with-keld/SKILL.md → backing-up-with-keld
			const parent = path.basename(path.dirname(filePath));
			if (parent && parent !== "skills") {
				skills.add(parent);
			}
		}
	}
	return [...skills].sort();
}

/**
 * Resolve the model to use for handoff extraction calls. Uses --handoff-model,
 * PI_HANDOFF_MODEL, then handoffModel in user settings, falling back to the
 * session model if no valid override is configured.
 */
export function resolveExtractionModel(
	pi: ExtensionAPI,
	ctx: {
		cwd: string;
		model: ExtensionContext["model"];
		modelRegistry: ExtensionContext["modelRegistry"];
	},
): ExtensionContext["model"] {
	const modelSpec = configuredHandoffModel(pi, ctx);
	if (!modelSpec) return ctx.model;
	const parsed = parseModelSpec(modelSpec);
	if (!parsed) return ctx.model;
	return ctx.modelRegistry.find(parsed.provider, parsed.modelId) ?? ctx.model;
}
