import { Client, type l } from "@atproto/lex";
import * as getPostThread from "@/lib/lexicons/app/bsky/feed/getPostThread";
import * as feedDefs from "@/lib/lexicons/app/bsky/feed/defs";

const atprotoClient = new Client("https://public.api.bsky.app");

export type BlueskyPost = feedDefs.ThreadViewPost;

export type LinkMetadata = {
  uri: string;
  title: string;
  description: string;
  thumb?: string;
};

export function blueskyUrlToAtUri(url: string): string | null {
  try {
    const urlObj = new URL(url);
    const pathParts = urlObj.pathname.split("/").filter(Boolean);
    if (pathParts[0] === "profile" && pathParts[2] === "post" && pathParts.length >= 4) {
      return `at://${pathParts[1]}/app.bsky.feed.post/${pathParts[3]}`;
    }
    return null;
  } catch {
    return null;
  }
}

export async function getBlueskyPost(uri: string): Promise<BlueskyPost | null> {
  const atUri = uri.startsWith("at://")
    ? uri
    : uri.startsWith("http")
      ? blueskyUrlToAtUri(uri)
      : null;
  if (!atUri) return null;

  try {
    const result = await atprotoClient.call(getPostThread.main, {
      uri: atUri as l.AtUri,
      depth: 0,
      parentHeight: 0,
    });
    if (feedDefs.threadViewPost.$check(result.thread)) {
      return result.thread;
    }
    return null;
  } catch (error) {
    console.error("Failed to fetch Bluesky post:", error);
    return null;
  }
}

export async function getLinkMetadata(url: string): Promise<LinkMetadata | null> {
  try {
    const response = await fetch(
      `https://cardyb.bsky.app/v1/extract?url=${encodeURIComponent(url)}`,
    );
    if (!response.ok) return null;

    const data = await response.json();
    return {
      uri: url,
      title: data.title || url,
      description: data.description || "",
      thumb: data.image || undefined,
    };
  } catch (error) {
    console.error("Failed to fetch link metadata:", error);
    return null;
  }
}
