import { buildAuditEnvelope, emitUokAuditEvent } from "./audit.js";
import { buildModelRouteSnapshot } from "./model-route-snapshot.js";

/**
 * Return the model role implied by an autonomous unit type.
 *
 * Purpose: keep SF's durable model policy role-based (`worker`, `validator`,
 * `reviewer`) while still allowing the dispatcher to journal the concrete
 * provider/model chosen at runtime.
 *
 * Consumer: auto/phases.js after selectAndApplyModel resolves the final unit
 * model, including hook overrides.
 */
export function modelRoleForUnitType(unitType) {
	const normalized = String(unitType ?? "").toLowerCase();
	if (
		normalized.includes("validate") ||
		normalized.includes("verification") ||
		normalized.includes("gate")
	) {
		return "validator";
	}
	if (normalized.includes("review") || normalized.includes("scrutiny")) {
		return "reviewer";
	}
	if (
		normalized.includes("adversar") ||
		normalized.includes("challenge") ||
		normalized.includes("red-team") ||
		normalized.includes("redteam")
	) {
		return "adversary";
	}
	return "worker";
}

/**
 * Emit runtime evidence for SF's auto-selected model route.
 *
 * Purpose: preserve the useful Droid-style role/accounting trail without
 * promoting provider-specific model IDs into durable SF configuration.
 *
 * Consumer: autonomous run-unit dispatch telemetry and UOK audit readers.
 */
export function emitModelAutoResolvedEvent(basePath, args) {
	const model = args.resolvedModel;
	const provider = model?.provider ?? null;
	const modelId = model?.id ?? null;
	const role = args.role ?? modelRoleForUnitType(args.unitType);
	const requestedPolicy = {
		mode: "auto",
		constraints: args.constraints ?? [],
	};
	const routeSnapshot = buildModelRouteSnapshot({
		role,
		unitType: args.unitType,
		unitId: args.unitId,
		requestedPolicy,
		route: {
			...(model ?? {}),
			authMode: args.authMode,
		},
		routingReason: args.routingReason,
		fallbacksTried: args.fallbacksTried ?? [],
		configEvidence: args.configEvidence,
	});
	emitUokAuditEvent(
		basePath,
		buildAuditEnvelope({
			traceId: args.traceId,
			turnId: args.unitId,
			category: "model-routing",
			type: "model-auto-resolved",
			payload: {
				role,
				unitType: args.unitType,
				unitId: args.unitId,
				requestedPolicy,
				resolvedProvider: provider,
				resolvedModel: modelId,
				authMode: args.authMode,
				routeSnapshot,
				routingReason: args.routingReason,
				fallbacksTried: args.fallbacksTried ?? [],
				routing: args.routing ?? null,
				hookOverrideApplied: Boolean(args.hookOverrideApplied),
				tokenUsage: args.tokenUsage,
				costEstimate: args.costEstimate,
			},
		}),
	);
}
