import type { CodeResult } from "$lib/components/search/types";
import { authedGet, type AppviewContext } from "./appview";
import type { BobbinContext, XrpcRequestInit } from "./client";
import { jsonGet } from "./_request";
import { paginateBy } from "./pagination";
import * as OrgTangledTempSearchSearchCode from "./lexicons/types/org/tangled/temp/search/searchCode";

export interface SearchHit {
	uri: string;
	cid?: string;
	nsid: string;
	score: number;
	/** the indexed record; shape varies by `nsid`. */
	value: unknown;
}

export interface SearchPage {
	hits: SearchHit[];
	cursor: string | null;
}

export interface SearchParams {
	q: string;
	nsid?: string;
	author?: string;
	repo?: string;
	since?: string;
	until?: string;
	cursor?: string;
	limit?: number;
}

export const search = (ctx: BobbinContext, params: SearchParams, init?: XrpcRequestInit) =>
	jsonGet<SearchPage>(ctx, "sh.tangled.search.query", { ...params }, init);

export interface SearchAllOptions extends XrpcRequestInit {
	maxPages?: number;
}

/** Async-iterate every search hit across cursor pages. */
export async function* searchAll(
	ctx: BobbinContext,
	params: Omit<SearchParams, "cursor">,
	options: SearchAllOptions = {}
): AsyncGenerator<SearchHit, void, unknown> {
	yield* paginateBy<SearchHit>(async (cursor) => {
		const page = await search(ctx, { ...params, cursor }, options);
		return { items: page.hits, cursor: page.cursor };
	}, options);
}

export interface CodeSearchPage {
	results: CodeResult[];
	cursor: string | null;
}

export const searchCode = async (
	ctx: AppviewContext,
	params: OrgTangledTempSearchSearchCode.$params,
	init?: XrpcRequestInit
): Promise<CodeSearchPage> => {
	const out = await authedGet<OrgTangledTempSearchSearchCode.$output>(
		ctx,
		OrgTangledTempSearchSearchCode.mainSchema.nsid,
		{ ...params },
		init
	);
	console.info("[searchCode] live response", out);

    // TODO: pass down results
	return { results: fakeResultsFor(params.q), cursor: null };
};

const fakeResultsFor = (q: string): CodeResult[] => {
	const lang = /(?:^|\s)lang:(\S+)/i.exec(q)?.[1]?.toLowerCase();
	return lang ? FAKE_RESULTS.filter((r) => r.language?.toLowerCase() === lang) : FAKE_RESULTS;
};

const FAKE_RESULTS: CodeResult[] = [
	{
		repoDid: "did:plc:wshs7t2adsemcrrd4snkeqli",
		ownerHandle: "alice.tangled.sh",
		repoName: "knotserver",
		ref: "main",
		path: "cmd/knot/main.go",
		language: "Go",
		chunks: [
			{
				content:
					'func main() {\n\tif err := run(); err != nil {\n\t\tlog.Fatal("main:", err)\n\t}\n}',
				lineStart: 24,
				highlights: [
					{ start: 5, end: 9 },
					{ start: 58, end: 62 }
				]
			}
		]
	},
	{
		repoDid: "did:plc:wshs7t2adsemcrrd4snkeqli",
		ownerHandle: "bob.tangled.sh",
		repoName: "web",
		ref: "main",
		path: "src/lib/api/client.ts",
		language: "TypeScript",
		chunks: [
			{
				content:
					"export interface BobbinContext {\n\tserviceUrl: string;\n\tfetch: typeof fetch;\n}",
				lineStart: 7,
				highlights: [{ start: 17, end: 30 }]
			},
			{
				content:
					"export const createBobbinClient = (init: ClientInit): BobbinContext => ({\n\tserviceUrl: init.serviceUrl,",
				lineStart: 19,
				highlights: [{ start: 13, end: 31 }]
			},
			{
				content: "\t\treturn createBobbinClient({ serviceUrl, fetch });",
				lineStart: 41,
				highlights: [{ start: 9, end: 27 }]
			},
			{
				content: "// createBobbinClient is the only place the service url is normalised",
				lineStart: 58,
				highlights: [{ start: 3, end: 21 }]
			},
			{
				content: "const ctx = createBobbinClient({ serviceUrl: BOBBIN });",
				lineStart: 73,
				highlights: [{ start: 12, end: 30 }]
			}
		]
	},
	{
		repoDid: "did:plc:wshs7t2adsemcrrd4snkeqli",
		ownerHandle: "carol.tangled.sh",
		repoName: "notes",
		ref: "trunk",
		path: "docs/naïve-search.md",
		chunks: [
			{
				// non-ascii and a blank line, to prove the byte-offset split
				content: "# naïve search\n\nthe naïve approach walks every document.",
				lineStart: 1,
				highlights: [
					{ start: 2, end: 8 },
					{ start: 21, end: 27 }
				]
			}
		]
	}
];
