// VibnCode Agent Marketplace API
// Built with Hono and Bun

import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { prettyJSON } from 'hono/pretty-json';
import { checkDatabaseConnection } from './db/client';
import { errorHandler } from './middlewares/error-handler';
import agentRoutes from './routes/agents';
import analyticsRoutes from './routes/analytics';
// Import routes
import authRoutes from './routes/auth';
import marketplaceRoutes from './routes/marketplace';
import modelsRoutes from './routes/models';
import remoteAgentsRoutes from './routes/remote-agents';
import remoteSkillsRoutes from './routes/remote-skills';
import searchRoutes from './routes/search';
import shareRoutes from './routes/shares';
import skillRoutes from './routes/skills';
import skillsMarketplaceRoutes from './routes/skills-marketplace';
import vibncodeProviderRoutes from './routes/vibncode-provider';
import updatesRoutes from './routes/updates';
import userRoutes from './routes/users';
import webFetchRoutes from './routes/web-fetch';
import type { HonoContext } from './types/context';

const app = new Hono<HonoContext>();

// Auto-run migrations on startup if using local SQLite fallback inside container
const isBunRuntime = typeof Bun !== 'undefined';
if (isBunRuntime && !Bun.env.TURSO_DATABASE_URL) {
  console.log('[Startup] Auto-running database migrations for local SQLite...');
  try {
    const proc = Bun.spawnSync(["bun", "run", "src/db/migrate.ts"]);
    console.log('[Startup] Migration output:', proc.stdout?.toString());
    if (proc.stderr && proc.stderr.length > 0) {
      console.error('[Startup] Migration error:', proc.stderr.toString());
    }
  } catch (err) {
    console.error('[Startup] Failed to run database migrations on boot:', err);
  }
}

// Determine if running in development mode
const isDevelopment = typeof Bun !== 'undefined' ? Bun.env.NODE_ENV !== 'production' : false;

// CORS origins based on environment
const corsOrigins: string[] = [
  'tauri://localhost', // Tauri app always needs access
];

// Only allow localhost origins in development
if (isDevelopment) {
  corsOrigins.push('http://localhost:1420', 'http://localhost:5173');
}

// Global middlewares
app.use('*', logger());
app.use('*', prettyJSON());
app.use(
  '*',
  cors({
    origin: corsOrigins,
    credentials: true,
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-Device-ID'],
    exposeHeaders: ['X-VibnCode-Remaining-Tokens'],
  })
);

// Initialize database connection for Cloudflare Workers
app.use('*', async (c, next) => {
  if (c.env) {
    // Initialize DB with environment variables from Cloudflare Workers
    const { getDb } = await import('./db/client');
    getDb(c.env);
  }
  await next();
});

// Health check endpoint
app.get('/health', async (c) => {
  const dbHealthy = await checkDatabaseConnection(c.env);
  const runtime = typeof Bun !== 'undefined' ? 'bun' : 'cloudflare-workers';
  const version = typeof Bun !== 'undefined' ? Bun.version : 'n/a';

  return c.json({
    status: 'ok',
    runtime,
    version,
    database: dbHealthy ? 'connected' : 'disconnected',
    timestamp: new Date().toISOString(),
  });
});

// API info
app.get('/', (c) => {
  return c.json({
    name: 'VibnCode Agent Marketplace API',
    version: '1.0.0',
    docs: '/api/docs',
    health: '/health',
  });
});

// Standalone Auth Landing Page for Desktop SSO redirection
app.get('/auth', (c) => {
  return c.html(`
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Sign In to VibnCode</title>
      <style>
        :root { color-scheme: dark; }
        body {
          margin: 0;
          min-height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
          background: radial-gradient(circle at 20% 20%, #1c1c1f, #0b0b0f 60%);
          color: #f5f5f5;
          font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
          letter-spacing: 0.01em;
        }
        .card {
          border: 1px solid rgba(255, 255, 255, 0.08);
          background: rgba(12, 12, 16, 0.85);
          border-radius: 20px;
          padding: 40px;
          box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
          backdrop-filter: blur(16px);
          text-align: center;
          width: min(400px, 90vw);
        }
        .logo {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 52px;
          height: 52px;
          border-radius: 12px;
          background: linear-gradient(135deg, #3b82f6, #6366f1);
          font-size: 24px;
          margin-bottom: 20px;
          color: white;
          font-weight: bold;
        }
        h1 { margin: 0 0 8px; font-size: 24px; font-weight: 600; color: #f8f8f8; }
        p { margin: 0 0 28px; color: #b6b6bd; font-size: 14px; line-height: 1.5; }
        .button {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 10px;
          width: 100%;
          padding: 12px;
          border-radius: 999px;
          border: 1px solid rgba(255, 255, 255, 0.15);
          background: rgba(255, 255, 255, 0.06);
          color: #ffffff;
          text-decoration: none;
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 12px;
          transition: background 0.2s, transform 0.1s;
        }
        .button:hover {
          background: rgba(255, 255, 255, 0.12);
          transform: translateY(-1px);
        }
        .button:active {
          transform: translateY(0);
        }
      </style>
    </head>
    <body>
      <div class="card">
        <div class="logo">V</div>
        <h1>Sign In to VibnCode</h1>
        <p>Connect your desktop client securely to your workspace cloud containers.</p>
        <a class="button" href="/api/auth/github">Sign In with GitHub</a>
        <a class="button" href="/api/auth/google">Sign In with Google</a>
      </div>
    </body>
    </html>
  `);
});

// API routes
app.route('/api/auth', authRoutes);
app.route('/api/marketplace', marketplaceRoutes);
app.route('/api/skills-marketplace', skillsMarketplaceRoutes);
app.route('/api/agents', agentRoutes);
app.route('/api/skills', skillRoutes);
app.route('/api/users', userRoutes);
app.route('/api/models', modelsRoutes);
app.route('/api/remote-skills', remoteSkillsRoutes);
app.route('/api/remote-agents', remoteAgentsRoutes);
app.route('/api/updates', updatesRoutes);
app.route('/api/analytics', analyticsRoutes);
app.route('/api/vibncode', vibncodeProviderRoutes);
app.route('/api/search', searchRoutes);
app.route('/api/shares', shareRoutes);
app.route('/api/web-fetch', webFetchRoutes);

// 404 handler
app.notFound((c) => {
  return c.json({ error: 'Not found' }, 404);
});

// Error handler
app.onError(errorHandler);

// Conditional export based on runtime environment
// Check if we're running in Bun (local dev) or Cloudflare Workers

// Scheduled handler for cron triggers (Cloudflare Workers only)
export async function scheduled(
  event: ScheduledEvent,
  env: HonoContext['env'],
  _ctx: ExecutionContext
) {
  console.log('[Cron] Running scheduled task:', event.cron);

  try {
    // Initialize database
    const { getDb } = await import('./db/client');
    const { db } = getDb(env);

    // Import and run cleanup
    const { ShareService } = await import('./services/share-service');
    const shareService = new ShareService(db);
    const deletedCount = await shareService.cleanupExpiredShares();

    console.log(`[Cron] Cleaned up ${deletedCount} expired shares`);
  } catch (error) {
    console.error('[Cron] Failed to run cleanup:', error);
  }
}

// Export for Cloudflare Workers (when Bun is not available)
// Export for Bun runtime (when Bun is available)
export default isBunRuntime
  ? {
      port: parseInt(Bun.env.PORT || '3000', 10),
      fetch: app.fetch,
      development: Bun.env.NODE_ENV !== 'production',
    }
  : app;

// Also export the app explicitly for Cloudflare Workers compatibility
export { app };
