import "dotenv/config";
import { existsSync } from "node:fs";
import { closeDb, ensureSchema, getDb, getDbPath } from "../server/db.js";
import { correctCity, getActiveProviderInfo } from "../server/ai/index.js";

// One round-trip against the active AI provider. Override the test input with:
//   TEST_CITY="Brooklyn" TEST_STATE="NY" npm run ai:smoke
const TEST_CITY = process.env.TEST_CITY || "Hosuton";
const TEST_STATE = (process.env.TEST_STATE || "TX").toUpperCase();

function pad(s, n) { return String(s).padEnd(n); }

async function main() {
  if (!existsSync(getDbPath())) {
    console.error(`✗ DB not found at ${getDbPath()}\n  Run:  npm run gazetteer:load`);
    process.exit(2);
  }

  const info = getActiveProviderInfo();
  if (!info.available) {
    console.error(`✗ No AI provider configured.\n  ${info.reason}`);
    process.exit(2);
  }

  console.log("─".repeat(60));
  console.log(`${pad("Provider", 10)} ${info.provider}`);
  console.log(`${pad("Model", 10)} ${info.model}`);
  console.log(`${pad("Input", 10)} "${TEST_CITY}", ${TEST_STATE}`);
  console.log("─".repeat(60));

  const db = getDb();
  ensureSchema(db);
  const rows = db.prepare("SELECT DISTINCT name FROM gazetteer_places WHERE state_code = ?").all(TEST_STATE);
  const candidates = rows.map((r) => r.name).sort();
  if (candidates.length === 0) {
    console.error(`✗ No gazetteer rows for state ${TEST_STATE}. Is the DB loaded?`);
    process.exit(2);
  }

  const started = Date.now();
  let result;
  try {
    result = await correctCity({ city: TEST_CITY, stateCode: TEST_STATE, candidates });
  } catch (err) {
    console.error(`\n✗ Provider call failed: ${err.message}`);
    if (err.stack && process.env.DEBUG) console.error(err.stack);
    process.exit(1);
  }
  const elapsed = Date.now() - started;

  const u = result.usage || {};
  console.log(`${pad("Corrected", 10)} ${result.correctedCityName ?? "(null)"}`);
  console.log(`${pad("Confidence", 10)} ${result.confidence}`);
  console.log(`${pad("Reasoning", 10)} ${result.reasoning || "—"}`);
  console.log("─".repeat(60));
  console.log(`${pad("Candidates", 10)} ${candidates.length.toLocaleString()}`);
  console.log(`${pad("Elapsed", 10)} ${elapsed} ms`);
  console.log(`${pad("Tokens", 10)} input=${u.input_tokens ?? 0}  output=${u.output_tokens ?? 0}` +
              (u.cache_read_input_tokens ? `  cache_read=${u.cache_read_input_tokens}` : "") +
              (u.cache_creation_input_tokens ? `  cache_write=${u.cache_creation_input_tokens}` : ""));
  console.log(`${pad("Cost", 10)} $${(result.costUsd ?? 0).toFixed(5)}`);
  console.log("─".repeat(60));
  console.log(`✓ ${result.provider} OK`);
}

try { await main(); }
catch (err) { console.error("\n✗ Unexpected:", err.message); process.exit(1); }
finally { closeDb(); }
