#!/usr/bin/env node
import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import {
  trace,
  enableVerboseTracing,
  createTracedDatabase,
  traceStep
} from "./index.js";
function getEnv(key, defaultValue) {
  const value = process.env[key];
  if (value === void 0) {
    if (defaultValue !== void 0) return defaultValue;
    throw new Error(`Environment variable ${key} is required`);
  }
  return value;
}
function getOptionalEnv(key) {
  return process.env[key];
}
class ExampleService {
  data = /* @__PURE__ */ new Map();
  async fetchData(id) {
    await this.delay(50);
    if (id === "error") {
      throw new Error("Simulated API error");
    }
    return { id, value: Math.random() };
  }
  async processData(data) {
    return traceStep("Data validation", async () => {
      await this.delay(20);
      if (!data.id) {
        throw new Error("Invalid data: missing ID");
      }
      return traceStep("Data transformation", async () => {
        await this.delay(30);
        return {
          ...data,
          processed: true,
          timestamp: Date.now()
        };
      });
    });
  }
  cacheData(key, value) {
    trace.traceSync("function", "cacheData", { key, value }, () => {
      this.data.set(key, value);
    });
  }
  delay(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}
async function databaseExample() {
  return trace.step("Database operations example", async () => {
    const db = createTracedDatabase(":memory:");
    db.exec(`
      CREATE TABLE users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        email TEXT UNIQUE,
        created_at INTEGER DEFAULT (strftime('%s', 'now'))
      )
    `);
    const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    insert.run("Alice", "alice@example.com");
    insert.run("Bob", "bob@example.com");
    const select = db.prepare("SELECT * FROM users WHERE name = ?");
    const user = select.get("Alice");
    const complex = db.prepare(`
      SELECT 
        name,
        COUNT(*) as count,
        MAX(created_at) as latest
      FROM users
      GROUP BY name
      HAVING COUNT(*) > 0
    `);
    const results = complex.all();
    db.close();
    return { user, results };
  });
}
async function runDemo() {
  console.log("\n" + "=".repeat(80));
  console.log("STACKMEMORY DEBUG TRACE DEMO");
  console.log("=".repeat(80) + "\n");
  if (process.env["DEBUG_TRACE"] !== "true") {
    console.log("Enabling verbose tracing for this demo...\n");
    enableVerboseTracing();
  }
  try {
    await trace.command("demo:service", { example: "service" }, async () => {
      const service = new ExampleService();
      console.log("\n--- Example 1: Service Operations ---\n");
      const data = await service.fetchData("test-1");
      const processed = await service.processData(data);
      service.cacheData("test-1", processed);
      console.log("Service operation completed\n");
    });
    await trace.command("demo:database", { example: "database" }, async () => {
      console.log("\n--- Example 2: Database Operations ---\n");
      const results = await databaseExample();
      console.log("Database operations completed");
      console.log("   Found user:", results.user);
      console.log("   Query results:", results.results);
    });
    await trace.command("demo:errors", { example: "errors" }, async () => {
      console.log("\n--- Example 3: Error Handling ---\n");
      const service = new ExampleService();
      try {
        await service.fetchData("error");
      } catch (error) {
        console.log("Error properly traced and handled\n");
      }
    });
    await trace.command(
      "demo:performance",
      { example: "performance" },
      async () => {
        console.log("\n--- Example 4: Performance Tracking ---\n");
        await trace.step("Slow operation", async () => {
          await new Promise((resolve) => setTimeout(resolve, 150));
        });
        for (let i = 0; i < 3; i++) {
          await trace.step(`Fast operation ${i + 1}`, async () => {
            await new Promise((resolve) => setTimeout(resolve, 10));
          });
        }
        console.log("Performance tracking completed\n");
      }
    );
  } catch (error) {
    console.error("Demo failed:", error);
  }
  console.log("\n" + trace.getExecutionSummary());
  const traces = trace.exportTraces();
  console.log(`
Total traces collected: ${traces.length}`);
  if (traces.length > 0) {
    console.log("\nExample trace entry:");
    console.log(JSON.stringify(traces[0], null, 2));
  }
}
if (import.meta.url === `file://${process.argv[1]}`) {
  runDemo().catch(console.error);
}
export {
  runDemo
};
//# sourceMappingURL=trace-demo.js.map
