import { parseAgentEnv } from "@code/env/agent";
import { WorkAttemptExecutionError } from "@code/primitives/execution-runtime";
import { registerProvider } from "@flue/runtime";
import type { Fetchable } from "@flue/runtime/routing";
import { flue } from "@flue/runtime/routing";
import { Hono } from "hono";

import {
  cancelAgentOsAttempt,
  executeAgentOsAttempt,
  runtimeRegistry,
} from "./runtime/agent-os";

const agentEnv = parseAgentEnv(process.env);

registerProvider(agentEnv.AGENT_MODEL_PROVIDER, {
  api: agentEnv.AGENT_MODEL_API,
  apiKey:
    agentEnv.AGENT_MODEL_PROVIDER === "openrouter"
      ? (agentEnv.OPENROUTER_API_KEY ?? agentEnv.AGENT_MODEL_API_KEY)
      : agentEnv.AGENT_MODEL_API_KEY,
  baseUrl: agentEnv.AGENT_MODEL_BASE_URL,
  models: {
    [agentEnv.AGENT_MODEL_NAME]: {
      contextWindow: agentEnv.AGENT_MODEL_CONTEXT_WINDOW,
      maxTokens: agentEnv.AGENT_MODEL_MAX_TOKENS,
    },
    "openai/gpt-oss-20b:free": {
      contextWindow: 131_072,
      maxTokens: agentEnv.AGENT_MODEL_MAX_TOKENS,
    },
  },
});

const app = new Hono();

app.post("/internal/work-attempts/execute", async (context) => {
  if (
    context.req.header("authorization") !== `Bearer ${agentEnv.FLUE_DB_TOKEN}`
  ) {
    return context.json({ error: "Unauthorized" }, 401);
  }
  try {
    return context.json(await executeAgentOsAttempt(await context.req.json()));
  } catch (error) {
    const failure =
      error instanceof WorkAttemptExecutionError
        ? error
        : new WorkAttemptExecutionError({
            message:
              error instanceof Error ? error.message : "Execution failed",
            reason: "HarnessFailed",
            retryable: false,
          });
    return context.json(
      {
        error: {
          message: failure.message,
          reason: failure.reason,
          retryable: failure.retryable,
        },
      },
      500
    );
  }
});

app.post("/internal/work-attempts/:workspaceKey/cancel", async (context) => {
  if (
    context.req.header("authorization") !== `Bearer ${agentEnv.FLUE_DB_TOKEN}`
  ) {
    return context.json({ error: "Unauthorized" }, 401);
  }
  const body = (await context.req.json()) as { attemptId?: unknown };
  if (typeof body.attemptId !== "string" || body.attemptId.length === 0) {
    return context.json({ error: "attemptId is required" }, 400);
  }
  await cancelAgentOsAttempt(context.req.param("workspaceKey"), body.attemptId);
  return context.json({ cancelled: true });
});

app.all("/api/rivet/*", (context) => runtimeRegistry.handler(context.req.raw));
app.route("/", flue());

export default app satisfies Fetchable;
