"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InstantDBSetupCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const spinner_1 = require("../utils/spinner");
const fileSystem_1 = require("../utils/fileSystem");
const child_process_1 = require("child_process");
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
class InstantDBSetupCommand {
    constructor() {
        this.fs = new fileSystem_1.FileSystemManager();
        this.spinner = new spinner_1.EnhancedSpinner("Setting up InstantDB...");
    }
    async execute(options) {
        const { mcp = true, auth = true, schema = true, components = true, skipAuth = false, skipSchema = false, skipComponents = false, appId, token, } = options;
        console.log(chalk_1.default.blue.bold("🚀 InstantDB + MCP Setup\n"));
        try {
            // Check if we're in a valid project
            if (!(await this.isValidProject())) {
                throw new Error("Not a valid MyContext project. Run 'mycontext init' first.");
            }
            // Check if context files exist
            if (!(await this.hasContextFiles())) {
                console.log(chalk_1.default.yellow("⚠️ Context files not found. Generating them first..."));
                console.log(chalk_1.default.gray("Run 'mycontext generate context' first, then retry this command."));
                return;
            }
            await this.setupInstantDB({
                mcp: mcp,
                auth: auth && !skipAuth,
                schema: schema && !skipSchema,
                components: components && !skipComponents,
                appId,
                token,
            });
            console.log(chalk_1.default.green.bold("\n✅ InstantDB + MCP setup completed!"));
            this.showNextSteps();
        }
        catch (error) {
            this.spinner.fail("InstantDB setup failed");
            throw error;
        }
    }
    async isValidProject() {
        const packageJsonPath = path.join(process.cwd(), "package.json");
        const mycontextDir = path.join(process.cwd(), ".mycontext");
        return ((await fs.pathExists(packageJsonPath)) &&
            (await fs.pathExists(mycontextDir)));
    }
    async hasContextFiles() {
        const brainPath = path.join(process.cwd(), ".mycontext", "context.json");
        const typesPath = path.join(process.cwd(), ".mycontext", "02-types.ts");
        return (await fs.pathExists(brainPath)) && (await fs.pathExists(typesPath));
    }
    async setupInstantDB(options) {
        console.log(chalk_1.default.blue("🚀 Setting up InstantDB with MCP integration...\n"));
        // Step 1: Install InstantDB dependencies including MCP
        this.spinner
            .start()
            .updateText("Installing InstantDB and MCP dependencies...");
        await this.installInstantDBDependencies(options.mcp);
        this.spinner.succeed("Dependencies installed");
        // Step 2: Initialize InstantDB CLI
        this.spinner.start().updateText("Initializing InstantDB...");
        await this.initializeInstantDB();
        this.spinner.succeed("InstantDB initialized");
        // Step 3: Setup MCP integration
        if (options.mcp) {
            this.spinner.start().updateText("Setting up MCP integration...");
            await this.setupMCPIntegration(options.token);
            this.spinner.succeed("MCP integration setup");
        }
        // Step 4: Generate schema from context
        if (options.schema) {
            this.spinner.start().updateText("Generating database schema...");
            await this.generateSchemaFromContext();
            this.spinner.succeed("Schema generated");
        }
        // Step 5: Generate auth components
        if (options.auth) {
            this.spinner.start().updateText("Setting up authentication...");
            await this.setupAuthentication();
            this.spinner.succeed("Authentication setup");
        }
        // Step 6: Generate database components
        if (options.components) {
            this.spinner.start().updateText("Generating database components...");
            await this.generateDatabaseComponents();
            this.spinner.succeed("Database components generated");
        }
        // Step 7: Update existing components with DB integration
        this.spinner
            .start()
            .updateText("Integrating database with existing components...");
        await this.integrateDatabaseWithComponents();
        this.spinner.succeed("Database integration complete");
        // Step 8: Create environment configuration
        this.spinner.start().updateText("Creating environment configuration...");
        await this.createEnvironmentConfig(options.appId);
        this.spinner.succeed("Environment configuration created");
    }
    async installInstantDBDependencies(includeMCP) {
        const packageManager = await this.detectPackageManager();
        const dependencies = ["@instantdb/react", "@instantdb/admin"];
        if (includeMCP) {
            dependencies.push("@instantdb/mcp");
        }
        try {
            (0, child_process_1.execSync)(`${packageManager} add ${dependencies.join(" ")}`, {
                stdio: "inherit",
                cwd: process.cwd(),
            });
        }
        catch (error) {
            console.log(chalk_1.default.yellow("⚠️ Failed to install with pnpm, trying npm..."));
            (0, child_process_1.execSync)(`npm install ${dependencies.join(" ")}`, {
                stdio: "inherit",
                cwd: process.cwd(),
            });
        }
    }
    async detectPackageManager() {
        if (await fs.pathExists(path.join(process.cwd(), "pnpm-lock.yaml"))) {
            return "pnpm";
        }
        return "npm";
    }
    async initializeInstantDB() {
        try {
            // Check if instant.schema.ts already exists
            const schemaPath = path.join(process.cwd(), "instant.schema.ts");
            if (await fs.pathExists(schemaPath)) {
                console.log(chalk_1.default.gray("   InstantDB already initialized"));
                return;
            }
            // Run instant-cli init
            (0, child_process_1.execSync)("npx instant-cli@latest init --yes", {
                stdio: "inherit",
                cwd: process.cwd(),
            });
        }
        catch (error) {
            console.log(chalk_1.default.yellow("⚠️ InstantDB CLI init failed, creating schema manually..."));
            await this.createBasicSchema();
        }
    }
    async setupMCPIntegration(token) {
        // Create MCP configuration
        const mcpConfigContent = `import { MCPServer } from "@instantdb/mcp";

// Initialize MCP server for InstantDB
const mcpServer = new MCPServer({
  // Use remote MCP server for production
  serverUrl: process.env.NODE_ENV === 'production' 
    ? 'https://mcp.instantdb.com/mcp'
    : 'https://mcp.instantdb.com/sse',
  
  // Local development with personal access token
  token: process.env.INSTANTDB_PERSONAL_ACCESS_TOKEN || '${token || "__YOUR_TOKEN__"}',
  
  // App configuration
  appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID || '__APP_ID__',
});

export { mcpServer };

// MCP utilities for MyContext integration
export const mcpUtils = {
  // Initialize MCP connection
  async initialize() {
    try {
      await mcpServer.connect();
      console.log('✅ MCP server connected to InstantDB');
      return { success: true };
    } catch (error) {
      console.error('❌ MCP connection failed:', error);
      return { success: false, error: error.message };
    }
  },

  // Create entities via MCP
  async createEntity(entityType: string, data: any) {
    try {
      const result = await mcpServer.createEntity(entityType, data);
      return { success: true, data: result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  // Query entities via MCP
  async queryEntities(query: any) {
    try {
      const result = await mcpServer.query(query);
      return { success: true, data: result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  // Update entities via MCP
  async updateEntity(entityType: string, id: string, data: any) {
    try {
      const result = await mcpServer.updateEntity(entityType, id, data);
      return { success: true, data: result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  // Delete entities via MCP
  async deleteEntity(entityType: string, id: string) {
    try {
      const result = await mcpServer.deleteEntity(entityType, id);
      return { success: true, data: result };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }
};
`;
        await fs.writeFile(path.join(process.cwd(), "lib", "mcp.ts"), mcpConfigContent);
        // Create MCP React hooks
        const mcpHooksContent = `"use client";

import { useState, useEffect } from 'react';
import { mcpUtils } from './mcp';

// Hook for MCP connection status
export function useMCPConnection() {
  const [isConnected, setIsConnected] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const initMCP = async () => {
      try {
        setIsLoading(true);
        const result = await mcpUtils.initialize();
        setIsConnected(result.success);
        setError(result.success ? null : result.error);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
        setIsConnected(false);
      } finally {
        setIsLoading(false);
      }
    };

    initMCP();
  }, []);

  return { isConnected, isLoading, error };
}

// Hook for real-time entity queries
export function useMCPQuery(entityType: string, query?: any) {
  const [data, setData] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsLoading(true);
        const result = await mcpUtils.queryEntities({ [entityType]: query || {} });
        
        if (result.success) {
          setData(result.data[entityType] || []);
          setError(null);
        } else {
          setError(result.error);
          setData([]);
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
        setData([]);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, [entityType, JSON.stringify(query)]);

  return { data, isLoading, error };
}

// Hook for entity mutations
export function useMCPMutation() {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const create = async (entityType: string, data: any) => {
    setIsLoading(true);
    setError(null);
    
    try {
      const result = await mcpUtils.createEntity(entityType, data);
      if (!result.success) {
        setError(result.error);
      }
      return result;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Unknown error';
      setError(errorMsg);
      return { success: false, error: errorMsg };
    } finally {
      setIsLoading(false);
    }
  };

  const update = async (entityType: string, id: string, data: any) => {
    setIsLoading(true);
    setError(null);
    
    try {
      const result = await mcpUtils.updateEntity(entityType, id, data);
      if (!result.success) {
        setError(result.error);
      }
      return result;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Unknown error';
      setError(errorMsg);
      return { success: false, error: errorMsg };
    } finally {
      setIsLoading(false);
    }
  };

  const remove = async (entityType: string, id: string) => {
    setIsLoading(true);
    setError(null);
    
    try {
      const result = await mcpUtils.deleteEntity(entityType, id);
      if (!result.success) {
        setError(result.error);
      }
      return result;
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Unknown error';
      setError(errorMsg);
      return { success: false, error: errorMsg };
    } finally {
      setIsLoading(false);
    }
  };

  return { create, update, remove, isLoading, error };
}
`;
        await fs.writeFile(path.join(process.cwd(), "lib", "mcp-hooks.ts"), mcpHooksContent);
        console.log(chalk_1.default.gray("   MCP integration files created"));
    }
    async createBasicSchema() {
        const schemaContent = `import { i } from "@instantdb/react";

const schema = i.schema({
  entities: {
    $users: i.entity({
      email: i.string().unique().indexed(),
      name: i.string(),
      createdAt: i.date(),
      updatedAt: i.date(),
    }),
    profiles: i.entity({
      userId: i.string(),
      nickname: i.string(),
      bio: i.string().optional(),
      avatar: i.string().optional(),
      createdAt: i.date(),
      updatedAt: i.date(),
    }),
    // Add more entities based on your project context
  },
  links: {
    userProfile: {
      forward: { on: "profiles", has: "one", label: "user" },
      reverse: { on: "$users", has: "one", label: "profile" },
    },
  },
});

export default schema;
`;
        await fs.writeFile(path.join(process.cwd(), "instant.schema.ts"), schemaContent);
    }
    async generateSchemaFromContext() {
        // Read context exports (derived from brain)
        const prdPath = path.join(process.cwd(), ".mycontext", "01-prd.md");
        const typesPath = path.join(process.cwd(), ".mycontext", "02-types.ts");
        const prd = await fs.readFile(prdPath, "utf-8");
        const types = await fs.readFile(typesPath, "utf-8");
        // Generate enhanced schema based on context
        const enhancedSchema = await this.buildEnhancedSchema(prd, types);
        // Update the schema file
        await fs.writeFile(path.join(process.cwd(), "instant.schema.ts"), enhancedSchema);
    }
    async buildEnhancedSchema(prd, types) {
        // Extract entities from types file
        const entities = this.extractEntitiesFromTypes(types);
        // Build schema with extracted entities
        let schemaContent = `import { i } from "@instantdb/react";

const schema = i.schema({
  entities: {
    $users: i.entity({
      email: i.string().unique().indexed(),
      name: i.string(),
      createdAt: i.date(),
      updatedAt: i.date(),
    }),
    profiles: i.entity({
      userId: i.string(),
      nickname: i.string(),
      bio: i.string().optional(),
      avatar: i.string().optional(),
      createdAt: i.date(),
      updatedAt: i.date(),
    }),
`;
        // Add extracted entities
        entities.forEach((entity) => {
            schemaContent += `    ${entity.name}: i.entity({\n`;
            entity.fields.forEach((field) => {
                const instantType = this.mapTypeToInstant(field.type);
                schemaContent += `      ${field.name}: i.${instantType}()${field.optional ? ".optional()" : ""},\n`;
            });
            schemaContent += `      createdAt: i.date(),\n`;
            schemaContent += `      updatedAt: i.date(),\n`;
            schemaContent += `    }),\n`;
        });
        schemaContent += `  },\n`;
        schemaContent += `  links: {\n`;
        schemaContent += `    userProfile: {\n`;
        schemaContent += `      forward: { on: "profiles", has: "one", label: "user" },\n`;
        schemaContent += `      reverse: { on: "$users", has: "one", label: "profile" },\n`;
        schemaContent += `    },\n`;
        schemaContent += `  },\n`;
        schemaContent += `});\n\n`;
        schemaContent += `export default schema;\n`;
        return schemaContent;
    }
    extractEntitiesFromTypes(typesContent) {
        const entities = [];
        // Simple regex to extract interfaces
        const interfaceRegex = /interface\s+(\w+)\s*\{([^}]+)\}/g;
        let match;
        while ((match = interfaceRegex.exec(typesContent)) !== null) {
            const name = match[1];
            const fieldsContent = match[2];
            const fields = [];
            const fieldRegex = /(\w+)(\?)?\s*:\s*([^;,\n]+)/g;
            let fieldMatch;
            while ((fieldMatch = fieldRegex.exec(fieldsContent || "")) !== null) {
                if (fieldMatch[1] && fieldMatch[3]) {
                    fields.push({
                        name: fieldMatch[1],
                        type: fieldMatch[3].trim(),
                        optional: !!fieldMatch[2],
                    });
                }
            }
            if (fields.length > 0 && name) {
                entities.push({ name: name.toLowerCase(), fields });
            }
        }
        return entities;
    }
    mapTypeToInstant(type) {
        const typeMap = {
            string: "string",
            number: "number",
            boolean: "boolean",
            Date: "date",
            object: "json",
            any: "any",
        };
        return typeMap[type] || "string";
    }
    async setupAuthentication() {
        // Create auth utilities
        const authUtilsContent = `import { init, id } from "@instantdb/react";
import schema from "./instant.schema";

const db = init({ 
  appId: process.env.NEXT_PUBLIC_INSTANT_APP_ID || "__APP_ID__", 
  schema 
});

export { db, id };

// Auth utilities
export const authUtils = {
  async sendMagicCode(email: string) {
    try {
      await db.auth.sendMagicCode({ email });
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  async signInWithMagicCode(email: string, code: string) {
    try {
      await db.auth.signInWithMagicCode({ email, code });
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  async signOut() {
    try {
      await db.auth.signOut();
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  async createUserProfile(userId: string, data: { nickname: string; bio?: string }) {
    try {
      await db.transact([
        db.tx.profiles[id()].create({
          userId,
          nickname: data.nickname,
          bio: data.bio || "",
          createdAt: Date.now(),
          updatedAt: Date.now(),
        })
      ]);
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }
};
`;
        await fs.writeFile(path.join(process.cwd(), "lib", "instantdb.ts"), authUtilsContent);
        // Create auth components
        await this.createAuthComponents();
    }
    async createAuthComponents() {
        // Create auth directory
        const authDir = path.join(process.cwd(), "components", "auth");
        await fs.ensureDir(authDir);
        // Create LoginForm component
        const loginFormContent = `"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { authUtils } from "@/lib/instantdb";
import { toast } from "sonner";

interface LoginFormProps {
  onSuccess?: () => void;
}

export function LoginForm({ onSuccess }: LoginFormProps) {
  const [email, setEmail] = useState("");
  const [code, setCode] = useState("");
  const [step, setStep] = useState<"email" | "code">("email");
  const [loading, setLoading] = useState(false);

  const handleSendCode = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email) return;

    setLoading(true);
    const result = await authUtils.sendMagicCode(email);
    setLoading(false);

    if (result.success) {
      setStep("code");
      toast.success("Magic code sent to your email!");
    } else {
      toast.error(result.error || "Failed to send code");
    }
  };

  const handleVerifyCode = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!code) return;

    setLoading(true);
    const result = await authUtils.signInWithMagicCode(email, code);
    setLoading(false);

    if (result.success) {
      toast.success("Successfully signed in!");
      onSuccess?.();
    } else {
      toast.error(result.error || "Invalid code");
    }
  };

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle>Sign In</CardTitle>
        <CardDescription>
          {step === "email" 
            ? "Enter your email to receive a magic code"
            : "Enter the code sent to your email"
          }
        </CardDescription>
      </CardHeader>
      <CardContent>
        {step === "email" ? (
          <form onSubmit={handleSendCode} className="space-y-4">
            <Input
              type="email"
              placeholder="Enter your email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? "Sending..." : "Send Magic Code"}
            </Button>
          </form>
        ) : (
          <form onSubmit={handleVerifyCode} className="space-y-4">
            <Input
              type="text"
              placeholder="Enter magic code"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              required
            />
            <div className="flex gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => setStep("email")}
                className="flex-1"
              >
                Back
              </Button>
              <Button type="submit" className="flex-1" disabled={loading}>
                {loading ? "Verifying..." : "Verify Code"}
              </Button>
            </div>
          </form>
        )}
      </CardContent>
    </Card>
  );
}
`;
        await fs.writeFile(path.join(authDir, "LoginForm.tsx"), loginFormContent);
        // Create UserDashboard component
        const userDashboardContent = `"use client";

import { db } from "@/lib/instantdb";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { authUtils } from "@/lib/instantdb";
import { toast } from "sonner";

export function UserDashboard() {
  const user = db.useUser();

  const handleSignOut = async () => {
    const result = await authUtils.signOut();
    if (result.success) {
      toast.success("Signed out successfully");
    } else {
      toast.error(result.error || "Failed to sign out");
    }
  };

  if (!user) {
    return null;
  }

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader>
        <CardTitle>Welcome, {user.email}!</CardTitle>
        <CardDescription>Your account dashboard</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div>
          <p className="text-sm text-muted-foreground">Email:</p>
          <p className="font-medium">{user.email}</p>
        </div>
        <div>
          <p className="text-sm text-muted-foreground">User ID:</p>
          <p className="font-mono text-xs">{user.id}</p>
        </div>
        <Button onClick={handleSignOut} variant="outline" className="w-full">
          Sign Out
        </Button>
      </CardContent>
    </Card>
  );
}
`;
        await fs.writeFile(path.join(authDir, "UserDashboard.tsx"), userDashboardContent);
        // Create AuthProvider component
        const authProviderContent = `"use client";

import { db } from "@/lib/instantdb";
import { LoginForm } from "./LoginForm";
import { UserDashboard } from "./UserDashboard";

export function AuthProvider() {
  return (
    <db.SignedIn>
      <UserDashboard />
    </db.SignedIn>
  );
}

export function AuthForm() {
  return (
    <db.SignedOut>
      <LoginForm />
    </db.SignedOut>
  );
}
`;
        await fs.writeFile(path.join(authDir, "AuthProvider.tsx"), authProviderContent);
        // Create index file
        const indexContent = `export { LoginForm } from "./LoginForm";
export { UserDashboard } from "./UserDashboard";
export { AuthProvider, AuthForm } from "./AuthProvider";
`;
        await fs.writeFile(path.join(authDir, "index.ts"), indexContent);
    }
    async generateDatabaseComponents() {
        // Create database utilities
        const dbUtilsContent = `import { db, id } from "@/lib/instantdb";

// Generic CRUD operations
export const dbUtils = {
  // Create operations
  async create(collection: string, data: any) {
    try {
      await db.transact([
        db.tx[collection][id()].create({
          ...data,
          createdAt: Date.now(),
          updatedAt: Date.now(),
        })
      ]);
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  // Read operations
  async read(collection: string, id: string) {
    try {
      const { data } = await db.query({ [collection]: { $: { where: { id } } } });
      return { success: true, data: data[collection]?.[0] };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  // Update operations
  async update(collection: string, id: string, data: any) {
    try {
      await db.transact([
        db.tx[collection][id].update({
          ...data,
          updatedAt: Date.now(),
        })
      ]);
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  // Delete operations
  async delete(collection: string, id: string) {
    try {
      await db.transact([
        db.tx[collection][id].delete()
      ]);
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  },

  // List operations
  async list(collection: string, filters?: any) {
    try {
      const query = filters ? { [collection]: { $: { where: filters } } } : { [collection]: {} };
      const { data } = await db.query(query);
      return { success: true, data: data[collection] || [] };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }
};

// Real-time hooks
export const useRealtimeQuery = (query: any) => {
  return db.useQuery(query);
};

export const useUser = () => {
  return db.useUser();
};
`;
        await fs.writeFile(path.join(process.cwd(), "lib", "db-utils.ts"), dbUtilsContent);
    }
    async integrateDatabaseWithComponents() {
        // Update existing components to use database
        const componentsDir = path.join(process.cwd(), "components");
        if (!(await fs.pathExists(componentsDir))) {
            return;
        }
        // This would scan existing components and add database integration
        // For now, we'll create a sample integration
        console.log(chalk_1.default.gray("   Database integration ready for existing components"));
    }
    async createEnvironmentConfig(appId) {
        const envContent = `# InstantDB Configuration
NEXT_PUBLIC_INSTANT_APP_ID=${appId || "__YOUR_APP_ID__"}

# InstantDB Personal Access Token (for MCP)
INSTANTDB_PERSONAL_ACCESS_TOKEN=__YOUR_PERSONAL_ACCESS_TOKEN__

# MCP Configuration
MCP_SERVER_URL=https://mcp.instantdb.com/mcp
MCP_SERVER_URL_SSE=https://mcp.instantdb.com/sse
`;
        const envPath = path.join(process.cwd(), ".env.local");
        const existingEnv = (await fs.pathExists(envPath))
            ? await fs.readFile(envPath, "utf-8")
            : "";
        // Only add InstantDB config if not already present
        if (!existingEnv.includes("INSTANT_APP_ID")) {
            await fs.writeFile(envPath, existingEnv + "\n" + envContent);
        }
    }
    showNextSteps() {
        console.log(chalk_1.default.blue.bold("\n🎯 Next Steps:\n"));
        console.log(chalk_1.default.yellow("1. Configure your InstantDB app:"));
        console.log(chalk_1.default.gray("   • Visit https://instantdb.com/dash"));
        console.log(chalk_1.default.gray("   • Create a new app or use existing one"));
        console.log(chalk_1.default.gray("   • Copy your APP_ID\n"));
        console.log(chalk_1.default.yellow("2. Get your Personal Access Token (for MCP):"));
        console.log(chalk_1.default.gray("   • Visit https://instantdb.com/dash/settings"));
        console.log(chalk_1.default.gray("   • Generate a Personal Access Token"));
        console.log(chalk_1.default.gray("   • Add it to your .env.local\n"));
        console.log(chalk_1.default.yellow("3. Update your environment variables:"));
        console.log(chalk_1.default.gray("   • Edit .env.local with your APP_ID and token"));
        console.log(chalk_1.default.gray("   • Example: NEXT_PUBLIC_INSTANT_APP_ID=your_app_id_here\n"));
        console.log(chalk_1.default.yellow("4. Push your schema to InstantDB:"));
        console.log(chalk_1.default.gray("   • Run: npx instant-cli@latest push"));
        console.log(chalk_1.default.gray("   • This will sync your schema with InstantDB\n"));
        console.log(chalk_1.default.yellow("5. Test your setup:"));
        console.log(chalk_1.default.gray("   • Import and use AuthProvider in your app"));
        console.log(chalk_1.default.gray("   • Test the magic code authentication flow\n"));
        console.log(chalk_1.default.yellow("6. Generate components with database integration:"));
        console.log(chalk_1.default.gray("   • Run: mycontext generate-components"));
        console.log(chalk_1.default.gray("   • Components will automatically include database features\n"));
        console.log(chalk_1.default.cyan("📚 Documentation:"));
        console.log(chalk_1.default.gray("   • InstantDB Docs: https://instantdb.com/docs"));
        console.log(chalk_1.default.gray("   • MCP Integration: https://github.com/instantdb/instant/tree/main/client/packages/mcp"));
        console.log(chalk_1.default.gray("   • Magic Code Auth: https://instantdb.com/docs/auth/magic-codes"));
    }
}
exports.InstantDBSetupCommand = InstantDBSetupCommand;
//# sourceMappingURL=setup-instantdb.js.map