import { hashText } from "./mvp-db";
import {
  extractPublishUrl,
  extractXhsPublishUrl,
  platformFromPublishUrl,
  safeHttpUrl,
  type SupportedPlatform,
} from "./publish-url";

export { extractXhsPublishUrl } from "./publish-url";

export function accountFromPublishLink(
  input: string,
  expectedPlatform?: SupportedPlatform,
) {
  const extracted = expectedPlatform
    ? extractPublishUrl(input, expectedPlatform)
    : extractXhsPublishUrl(input) || extractPublishUrl(input, "抖音");
  const url = safeHttpUrl(extracted);
  if (!url) return null;
  const platform = platformFromPublishUrl(url.toString());
  if (!platform || (expectedPlatform && platform !== expectedPlatform)) return null;
  const noteId =
    platform === "抖音"
      ? url.pathname.match(/\/(?:video|note)\/([A-Za-z0-9_-]{8,80})/)?.[1] ?? ""
      : url.pathname.match(
          /\/(?:discovery\/item|explore)\/([A-Za-z0-9_-]{8,80})/,
        )?.[1] ?? "";
  const platformUid = `pending-${hashText(
    noteId || `${url.origin}${url.pathname}`,
  )}`;
  return {
    platform,
    platformUid,
    nickname: "待识别账号",
    profileUrl: "",
  };
}
