// #region ValidationRunDetailPageLoad [C:2] [TYPE Module] [SEMANTICS validation, run, detail, report, load]
// @BRIEF SvelteKit load function for the validation run detail report page — fetches full run results including dashboards, issues, screenshots, dataset health, and logs.
// @RELATION CALLS -> [ValidationApi]
// @PRE policyId and runId route params are non-empty strings.
// @POST Returns { run } or redirects to 404 on missing run.
import { getValidationRunDetail } from '$lib/api.js';
import { error } from '@sveltejs/kit';
import type { PageLoad } from './$types';

// ── Type definitions for API boundary ─────────────────────────
interface RecordField {
	path?: string;
	label?: string;
	[key: string]: unknown;
}

interface RunRecord {
	id?: string;
	path?: string;
	execution_path?: string | null;
	screenshot_paths?: string[] | null;
	logs_sent_to_llm?: string[] | null;
	raw_response?: string | Record<string, unknown> | null;
	task_logs?: unknown[];
	[key: string]: unknown;
}

interface RunDetailResponse {
	run?: Record<string, unknown>;
	records?: RunRecord[];
}

interface ScreenshotEntry {
	path: string;
	label: string;
}

/** Extract a field from a record, falling back to raw_response JSON if top-level is empty. */
function extractFromRaw(rec: Record<string, unknown>, field: string): unknown[] {
	const val = rec[field];
	if (val && (Array.isArray(val) ? (val as unknown[]).length > 0 : true)) {
		return val as unknown[];
	}
	try {
		const raw = rec.raw_response;
		const parsed = typeof raw === 'string' ? JSON.parse(raw) : (raw || {});
		return (parsed as Record<string, unknown>)[field] as unknown[] || [];
	} catch {
		return [];
	}
}

/** Check if a record used Path A (screenshots) by looking at execution_path or screenshot_paths. */
function isPathA(rec: Record<string, unknown>): boolean {
	if (rec.path === 'A') return true;
	if (rec.execution_path === 'screenshot' || rec.execution_path === 'multimodal') return true;
	const shots = extractFromRaw(rec, 'screenshot_paths');
	return Array.isArray(shots) && shots.length > 0;
}

/** Extract a human-readable tab label from a screenshot path.
 *  Filename format: {dashboard_id}_{label}_{timestamp}_d{depth}.webp
 *  e.g. "11_Overview_1780300006_d0.webp" → "Overview"
 */
function tabLabelFromPath(shot: string | { path?: string }): string {
	const filePath = typeof shot === 'string' ? shot : (shot?.path || '');
	const basename = filePath.split('/').pop()?.replace(/\.\w+$/, '') || '';
	const match = basename.match(/^\d+_(.+)_\d+_d\d+$/);
	if (match) return match[1].replace(/_/g, ' ');
	const fallback = basename.match(/^\d+_(.+)_\d+$/);
	if (fallback) return fallback[1].replace(/_/g, ' ');
	return '';
}

export const load: PageLoad = async ({ params }) => {
	const { policyId, runId } = params as { policyId: string; runId: string };

	const runDetail: RunDetailResponse | null = await getValidationRunDetail(policyId, runId).catch(() => null);

	if (!runDetail) {
		error(404, 'Run not found');
	}

	// Normalise shape: merge records into run as dashboards for the report page
	const run = (runDetail.run || runDetail) as Record<string, unknown>;
	const records: RunRecord[] = runDetail.records || [];

	// Normalise field names from backend API shape to frontend template keys
	run.dashboards = records.map((rec: RunRecord) => {
		const rawShots = extractFromRaw(rec as Record<string, unknown>, 'screenshot_paths');
		const screenshots: ScreenshotEntry[] = rawShots.map((s: unknown) => {
			if (typeof s === 'string') return { path: s, label: tabLabelFromPath(s) };
			const obj = s as RecordField;
			return { path: obj.path || '', label: obj.label || tabLabelFromPath(obj.path || '') };
		});
		return {
			...rec,
			path: isPathA(rec as Record<string, unknown>) ? 'A' : 'B',
			screenshots,
			logs_sent: extractFromRaw(rec as Record<string, unknown>, 'logs_sent_to_llm'),
			task_logs: [] as unknown[], // will be loaded client-side on demand
		};
	});

	return { run };
};
// #endregion ValidationRunDetailPageLoad
