// arcrun cypher-executor Worker — AI 工作流執行引擎
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import type { ExecutionContext } from '@cloudflare/workers-types';
import type { Bindings } from './types';
import { handleScheduled } from './scheduled';
import { healthRouter } from './routes/health';
import { executeRouter } from './routes/execute';
import { cypherRouter } from './routes/cypher';
import { validateRouter } from './routes/validate';
import { docsRouter } from './routes/docs';
import { webhooksRouter } from './routes/webhooks';
import { webhooksCrudRouter } from './routes/webhooks-crud';
import { webhooksListRouter } from './routes/webhooks-list';
import { registerRouter } from './routes/register';
import { recipesRouter } from './routes/recipes';
import { credentialsRouter } from './routes/credentials';
import { webhooksNamedRouter } from './routes/webhooks-named';
import { authRouter } from './routes/auth';
import { resumeRouter } from './routes/resume';
import { executionsRouter } from './routes/executions';
import { initSeedRouter } from './routes/init-seed';
import { kbdbProxyRouter } from './routes/kbdb-proxy';
import { consoleRouter } from './routes/console';
import { consoleAuthRouter } from './routes/console-auth';
import { consoleDashboardRouter } from './routes/console-dashboard';
import { portalRouter } from './routes/portal';
import { portalDataRouter } from './routes/portal-data';
import { portalUiRouter } from './routes/portal-ui';

const app = new Hono<{ Bindings: Bindings }>();

// 全域 CORS（允許 arcrun.dev landing page 帶 credentials 存取）
app.use('*', cors({
  origin: ['https://arcrun.dev', 'https://www.arcrun.dev'],
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'X-Arcrun-API-Key'],
  credentials: true,
}));

// 掛載所有路由器
app.route('/', docsRouter);
app.route('/', healthRouter);
app.route('/', executeRouter);
app.route('/', cypherRouter);
app.route('/', validateRouter);
app.route('/', webhooksRouter);
app.route('/', webhooksNamedRouter);   // 必須在 webhooksCrudRouter 前（避免 /webhooks/:token 攔截 /webhooks/named）
app.route('/', webhooksCrudRouter);
app.route('/', webhooksListRouter);
app.route('/', registerRouter);
app.route('/', recipesRouter);
app.route('/', credentialsRouter);
app.route('/', authRouter);
app.route('/', resumeRouter);
app.route('/', executionsRouter);  // LI SDD M2.1: /executions/* + /workflows/:name/executions
app.route('/', initSeedRouter);    // 薄殼原則：seed recipe 是 API 行為（rule 07，壓測 §4.1）
app.route('/', kbdbProxyRouter);   // kbdb-base 9.5：KBDB 資料層 proxy（讓 CLI 透過 cypher 達 KBDB，純轉發）
app.route('/', consoleRouter);     // Arcrun#3：搜尋/控制台頁 v0（單檔 HTML+原生 JS，薄殼）
app.route('/', consoleAuthRouter); // Arcrun#3 發現②：console 專用簡單 email+password 登入（單一管理員帳密，非多租戶）
app.route('/', consoleDashboardRouter); // T-cockpit ②：駕駛艙 dashboard（聚合 KBDB dash_* entries，無需登入唯讀）
app.route('/', portalRouter);      // portal-auth P2（#24/#25）：RAG Portal 多人授權——用戶模型＋認證 API
app.route('/', portalDataRouter);  // portal-auth P3：/portal/data/* server-side enforce（owner_id＋library 注入，安全核心）
app.route('/', portalUiRouter);    // portal-auth P3：GET /portal 單檔 HTML 殼（登入/搜尋/設定；獨立於 console）

// Worker 導出（fetch + scheduled）
// scheduled handler 對應 wrangler.toml [triggers].crons，每分鐘 tick；
// 邏輯在 src/scheduled.ts。對應 SDD: arcrun.md 三-A P1 #3。
export default {
  fetch: app.fetch,
  scheduled: handleScheduled,
} satisfies ExportedHandler<Bindings>;
