/**
 * Shared PostHog client for server-side analytics.
 *
 * distinctId resolution:
 *   1. Synchronous boot — use the per-install instanceId UUID from settings.
 *      Events captured before OAuth resolves land under this ID; PostHog
 *      alias() later stitches them to the real account.
 *   2. Async on import — read the Claude Code OAuth keychain entry, fetch
 *      /api/oauth/profile, and reassign DISTINCT_ID to the Anthropic
 *      account UUID. Person properties (email, org, plan) get sent via
 *      posthog.identify(). All importers see the new ID via ES module live
 *      bindings, so no callsite changes are needed.
 *
 * If OAuth resolution fails (apiKey path, network down, expired token), we
 * stay on instanceId — events still flow, just under an opaque ID.
 */
import { PostHog } from "posthog-node";
import { instanceIdentity, resolveOauthIdentity } from "./identity";

export const posthog = new PostHog(process.env.POSTHOG_API_KEY!, {
  host: process.env.POSTHOG_HOST,
  enableExceptionAutocapture: true,
});

const boot = instanceIdentity();
/** Live-bound. Reassigned below when OAuth identity resolves. */
export let DISTINCT_ID: string = boot.distinctId;

// Identify under the instance ID immediately so a person record exists even
// for apiKey-mode users who never complete OAuth resolution.
posthog.identify({ distinctId: boot.distinctId, properties: boot.properties });

// Best-effort async upgrade to the real Anthropic identity.
(async () => {
  const oauth = await resolveOauthIdentity();
  if (!oauth) return;

  if (oauth.distinctId !== boot.distinctId) {
    // Tell PostHog the instanceId and the account UUID are the same person.
    // Past events on instanceId merge under the account UUID.
    try {
      posthog.alias({ distinctId: oauth.distinctId, alias: boot.distinctId });
    } catch (err) {
      console.warn("[posthog] alias failed:", err);
    }
  }

  posthog.identify({ distinctId: oauth.distinctId, properties: oauth.properties });
  DISTINCT_ID = oauth.distinctId;
})().catch((err) => console.warn("[posthog] identity upgrade failed:", err));
