export type LlmsCheckSuccess = {
  ok: true;
  exists: boolean;
  checkedUrl: string;
  statusCode: number;
  message: string;
};

export type LlmsCheckFailure = {
  ok: false;
  checkedUrl: string;
  statusCode?: number;
  error: string;
};

export type LlmsCheckResult = LlmsCheckSuccess | LlmsCheckFailure;

type LlmsCheckerOptions = {
  timeoutMs?: number;
};

const DEFAULT_TIMEOUT_MS = 7000;

export class LlmsCheckerService {
  private readonly timeoutMs: number;

  constructor(options: LlmsCheckerOptions = {}) {
    this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
  }

  async checkWebsiteForLlmsFile(originUrl: URL): Promise<LlmsCheckResult> {
    const llmsUrl = new URL("/llms.txt", originUrl.origin);
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), this.timeoutMs);

    try {
      const response = await fetch(llmsUrl.toString(), {
        method: "GET",
        redirect: "follow",
        signal: controller.signal,
        headers: {
          Accept: "text/plain, text/*;q=0.9,*/*;q=0.1",
        },
        cache: "no-store",
      });

      if (response.status === 404) {
        return {
          ok: true,
          exists: false,
          checkedUrl: llmsUrl.toString(),
          statusCode: response.status,
          message: "No llms.txt file was found at this website",
        };
      }

      if (!response.ok) {
        return {
          ok: false,
          checkedUrl: llmsUrl.toString(),
          statusCode: response.status,
          error: `Unable to check llms.txt (HTTP ${response.status})`,
        };
      }

      return {
        ok: true,
        exists: true,
        checkedUrl: llmsUrl.toString(),
        statusCode: response.status,
        message: "llms.txt file found",
      };
    } catch (error: unknown) {
      if (error instanceof Error && error.name === "AbortError") {
        return {
          ok: false,
          checkedUrl: llmsUrl.toString(),
          error: "The check timed out. Please try again.",
        };
      }

      return {
        ok: false,
        checkedUrl: llmsUrl.toString(),
        error: "Unable to reach that website. Please verify the URL and try again.",
      };
    } finally {
      clearTimeout(timeout);
    }
  }
}
