/**
 * Entity dump — prints every piece of data related to a single entity.
 */

import { query } from "../../db.js";

const SEP = "=".repeat(60);

/** Pretty-print a key-value pair with aligned columns. */
function kv(key: string, value: unknown): void {
  console.log(`  ${key.padEnd(20)}: ${value ?? ""}`);
}

/**
 * Fetch and display all data for the given entity ID:
 * entity row, content, relationships (in/out), identifiers, claims, annotations.
 */
export async function entityDump(entityId: string): Promise<void> {
  // ── Entity row ──────────────────────────────────────────────
  const { rows: entities } = await query(
    "SELECT * FROM entities WHERE id = $1",
    [entityId],
  );

  if (entities.length === 0) {
    console.log(`Entity not found: ${entityId}`);
    return;
  }

  const ent = entities[0];
  console.log(`\n${SEP}`);
  console.log(`ENTITY: ${ent.id}  [${ent.type}]`);
  console.log(SEP);

  for (const [k, v] of Object.entries(ent)) {
    if (k === "raw_json" || k === "fts") continue;
    kv(k, v);
  }

  // ── Content (latest 10) ─────────────────────────────────────
  const { rows: content } = await query(
    `SELECT id, type, LEFT(text, 120) AS text, published_at
     FROM content WHERE entity_id = $1
     ORDER BY published_at DESC LIMIT 10`,
    [entityId],
  );
  console.log("\n  CONTENT (latest 10):");
  for (const c of content) {
    console.log(`    [${c.type}] ${c.text ?? ""}  (${c.published_at})`);
  }

  // ── Relationships outgoing ──────────────────────────────────
  const { rows: outRels } = await query(
    `SELECT r.type, r.strength, r.evidence, e.name AS target_name
     FROM relationships r JOIN entities e ON r.target_id = e.id
     WHERE r.source_id = $1`,
    [entityId],
  );
  console.log("\n  RELATIONSHIPS (outgoing):");
  for (const r of outRels) {
    console.log(
      `    → ${r.target_name} [${r.type}] (${r.strength}%) — ${r.evidence}`,
    );
  }

  // ── Relationships incoming ──────────────────────────────────
  const { rows: inRels } = await query(
    `SELECT r.type, r.strength, r.evidence, e.name AS source_name
     FROM relationships r JOIN entities e ON r.source_id = e.id
     WHERE r.target_id = $1`,
    [entityId],
  );
  console.log("\n  RELATIONSHIPS (incoming):");
  for (const r of inRels) {
    console.log(
      `    ← ${r.source_name} [${r.type}] (${r.strength}%)`,
    );
  }

  // ── Identifiers ─────────────────────────────────────────────
  const { rows: idents } = await query(
    `SELECT type, value, country_code, carrier
     FROM identifiers WHERE entity_id = $1`,
    [entityId],
  );
  console.log("\n  IDENTIFIERS:");
  for (const i of idents) {
    console.log(
      `    ${i.type}: ${i.value}  (${i.country_code}) ${i.carrier ?? ""}`,
    );
  }

  // ── Claims ──────────────────────────────────────────────────
  const { rows: claims } = await query(
    `SELECT predicate, object, confidence, status, source
     FROM claims WHERE subject_id = $1 AND subject_type = 'entity'
     ORDER BY confidence DESC`,
    [entityId],
  );
  console.log("\n  CLAIMS:");
  for (const c of claims) {
    console.log(
      `    [${c.status}] ${c.predicate} → ${c.object}  (${c.confidence}%, ${c.source})`,
    );
  }

  // ── Annotations ─────────────────────────────────────────────
  const { rows: annotations } = await query(
    `SELECT analyst, LEFT(note, 200) AS note, confidence
     FROM annotations WHERE ref_id = $1
     ORDER BY confidence DESC NULLS LAST`,
    [entityId],
  );
  console.log("\n  ANNOTATIONS:");
  for (const a of annotations) {
    console.log(`    [${a.analyst}] (${a.confidence}%) ${a.note}`);
  }
}
