<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
import { getProfileShape } from '@auto-launch/fetchers/shape';
import { fetchWithTimeout, setStatus } from '@auto-launch/functions/helpers';
import { updateOption } from '@auto-launch/functions/wp';
import { overrideWithUrlParams } from '@auto-launch/state/url-params';
import { AI_HOST } from '@constants';
import { reqDataBasics } from '@shared/lib/data';
import { __ } from '@wordpress/i18n';
import { z } from 'zod';

const localShape = z.object({
	siteProfile: getProfileShape,
});

// No fallback here as we need this data
const url = `${AI_HOST}/api/site-profile`;
const method = 'POST';
const headers = { 'Content-Type': 'application/json' };

export const handleSiteProfile = async ({
	title,
	descriptionRaw,
	urlParams,
}) => {
	// translators: this is for a action log UI. Keep it short
	setStatus(__('Creating a site profile', 'extendify-local'));

	const body = JSON.stringify({
		...reqDataBasics,
		title: title || window.extSharedData.siteTitle,
		description: descriptionRaw,
		autoLaunch: true,
	});
	const response = await fetchWithTimeout(
		url,
		{ method, headers, body },
		20_000,
	);

	// This should throw rather than have a fallback
	if (!response?.ok) throw new Error('Failed to fetch site profile');

	// TODO: pull out followups here and save them for AI follow ups
	const { profile: p } = await response.json();
	const profile = getProfileShape.parse(p);
	// Overwrite with a few url params if provided
	const profileWIthUrlOverrides = {
		...profile,
		...overrideWithUrlParams(urlParams),
		descriptionRaw, // Add the raw description to profile
	};

	await updateOption(
		'extendify_site_profile',
		JSON.stringify(profileWIthUrlOverrides),
	);
	return localShape.parse({ siteProfile: profileWIthUrlOverrides });
};
