/**
 * Trust profile — the partner-grade method.
 *
 * Returns the answer to "is this agent trustworthy enough for this action?"
 * Combines Helixa identity score with Vaultfire bond posture.
 *
 * Powered by the live API at theloopbreaker.com — same JSON the Helixa demo
 * page uses. CORS-open, no auth, ~200ms p50 from Base mainnet.
 */

export interface AgentTrustProfile {
  address: string;
  /** 0–100, weighted blend of Cred + Flourishing + bonds + longevity + verification. */
  combinedScore: number;
  /** Verdict tier: unknown / identified (Helixa only) / committed (Vaultfire only) / trusted (both) / flagship (Cred≥80 + ≥3 bonds). */
  badge: 'unknown' | 'identified' | 'committed' | 'trusted' | 'flagship';
  /** Whether the agent has a Helixa identity registered. */
  hasIdentity: boolean;
  /** Active Vaultfire bonds (both partnership + accountability). */
  bondCount: number;
  /** Total ETH at stake across all active bonds. */
  stakedETH: string;
  /** 0–100 commitment-decay metric from the Flourishing Metric Oracle. */
  flourishingScore: number;
  /** Plain-English explainer of the enforcement model. */
  enforcement: string;
  /** API response time in ms. */
  tookMs: number;
}

export interface TrustClientOptions {
  /** Base URL. Defaults to the live theloopbreaker.com endpoint. */
  baseUrl?: string;
  /** Optional fetch override (e.g. for proxies, retries, edge runtimes). */
  fetch?: typeof fetch;
}

export class TrustModule {
  private baseUrl: string;
  private fetchImpl: typeof fetch;

  constructor(opts: TrustClientOptions = {}) {
    this.baseUrl = (opts.baseUrl ?? 'https://theloopbreaker.com').replace(/\/+$/, '');
    this.fetchImpl = opts.fetch ?? globalThis.fetch;
    if (!this.fetchImpl) {
      throw new Error(
        'No fetch implementation found. Pass `fetch` in options or use Node 18+.',
      );
    }
  }

  /**
   * Get an agent's combined trust profile. One HTTP call, eight fields.
   *
   * @example
   * const profile = await sdk.trust.getAgentTrustProfile('0xfA15...');
   * if (profile.combinedScore >= 50 && profile.bondCount >= 1) {
   *   // proceed with high-value action
   * }
   */
  async getAgentTrustProfile(address: string): Promise<AgentTrustProfile> {
    if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
      throw new Error(`Invalid Ethereum address: ${address}`);
    }
    const url = `${this.baseUrl}/api/helixa/trust?address=${address}&simple=1`;
    const res = await this.fetchImpl(url);
    if (!res.ok) {
      throw new Error(`Trust API returned ${res.status} ${res.statusText}`);
    }
    return (await res.json()) as AgentTrustProfile;
  }

  /**
   * Convenience: returns true if the agent meets a minimum trust threshold.
   * Defaults to score ≥ 30 (the "committed" or better range).
   */
  async isTrustedEnough(address: string, minScore = 30): Promise<boolean> {
    const profile = await this.getAgentTrustProfile(address);
    return profile.combinedScore >= minScore;
  }
}
