import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { TaskStatus } from "@agent-bounty/contracts";
import { sendTrafficAlert } from "@/lib/traffic-alert";
import { isIP } from "node:net";
import { evaluateExternalFunnelHealth } from "@/lib/traffic-conversion-monitor";
import crypto from "crypto";
import { AGENT_GATEWAY_URL, VIBEWORK_SITE_URL } from "@/lib/a2a-growth";

export const dynamic = "force-dynamic";

const MCP_API_BASE_URL = process.env.MCP_API_BASE_URL?.trim() || "https://agent.wooo.work";
const MCP_BOOTSTRAP_COMMAND =
  process.env.MCP_BOOTSTRAP_COMMAND?.trim() ||
  `API_KEY=<YOUR_MCP_KEY> API_BASE_URL=${MCP_API_BASE_URL} npx -y @agent-bounty/mcp-server`;

function getTaskPreview(description: string) {
  const sanitized = description.trim().replace(/\s+/g, " ");
  return {
    description_preview: sanitized.slice(0, 280),
    description_chars: sanitized.length,
    has_clear_steps: sanitized.includes("Step") || sanitized.includes("如何") || sanitized.includes("要求"),
  };
}

type PayoutTask = {
  reward_amount: number;
  stripe_checkout_session_id: string | null;
  stripe_payment_intent_id: string | null;
};

const getPayoutMode = (task: PayoutTask) => {
  if (task.stripe_checkout_session_id === "promo_free_bounty" && task.stripe_payment_intent_id) {
    return "BETA_ZERO_FRICTION";
  }
  if (task.stripe_payment_intent_id) {
    return "PAYMENT_AUTHORIZED";
  }
  return "PAYMENT_PENDING";
};

const AI_USER_AGENT_HINTS = [
  "gpt",
  "chatgpt",
  "openai",
  "anthropic",
  "claude",
  "perplexity",
  "llm",
  "mcp",
  "autogpt",
  "agent",
  "assistant",
  "gemini",
  "cursor",
  "copilot",
];
const REQUEST_ID_HEADERS = ["x-request-id", "x-correlation-id", "x-trace-id"];

function resolveRequestId(request: Request) {
  for (const headerName of REQUEST_ID_HEADERS) {
    const value = request.headers.get(headerName);
    if (value) {
      return value;
    }
  }
  return crypto.randomUUID();
}

function requestContext(request: Request) {
  return {
    request_id: resolveRequestId(request),
    user_agent: request.headers.get("user-agent") ?? "unknown",
    request_actor_headers: {
      x_agent_id: request.headers.get("x-agent-id") ?? null,
      x_agent_name: request.headers.get("x-agent-name") ?? null,
      x_ai_agent_id: request.headers.get("x-ai-agent-id") ?? null,
      x_ai_id: request.headers.get("x-ai-id") ?? null,
      x_request_id: request.headers.get("x-request-id") ?? null,
      origin: request.headers.get("origin") ?? null,
    },
  };
}

function normalizeActorId(value: string, fallback: string) {
  const cleaned = value.trim().toLowerCase().replace(/[^a-z0-9._:-]+/g, "_").replace(/_+/g, "_");
  return cleaned.slice(0, 64) || fallback;
}

function sanitizeIpAddress(value: string | undefined) {
  if (!value) {
    return undefined;
  }

  const first = value.split(",")[0]?.trim();
  if (!first) {
    return undefined;
  }

  const bracketedMatch = first.match(/^\[(.+)\]:(\d+)$/);
  if (bracketedMatch?.[1]) {
    return bracketedMatch[1].toLowerCase();
  }

  const ipv4WithPortMatch = first.match(/^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/);
  if (ipv4WithPortMatch?.[1]) {
    return ipv4WithPortMatch[1];
  }

  return first.toLowerCase();
}

function resolveSourceIp(request: Request) {
  return sanitizeIpAddress(
    request.headers.get("x-forwarded-for") ??
    request.headers.get("x-real-ip") ??
    request.headers.get("cf-connecting-ip") ??
    request.headers.get("true-client-ip") ??
    request.headers.get("x-client-ip") ??
    "unknown"
  );
}

function isPrivateIp(ip: string | undefined) {
  if (!ip) return true;
  const normalized = ip.trim().toLowerCase();
  if (!normalized) {
    return true;
  }
  if (normalized === "unknown" || normalized === "localhost") {
    return true;
  }
  if (normalized === "::1" || normalized.startsWith("fe80")) {
    return true;
  }
  if (isIP(normalized) === 6 && (normalized.startsWith("fc") || normalized.startsWith("fd"))) {
    return true;
  }
  if (isIP(normalized) === 0) {
    return false;
  }

  if (normalized.startsWith("127.") || normalized.startsWith("10.") || normalized.startsWith("192.168.")) {
    return true;
  }

  if (normalized.startsWith("172.")) {
    const secondOctet = Number(normalized.split(".")[1]);
    return secondOctet >= 16 && secondOctet <= 31;
  }

  return false;
}

function isLikelyAIAgentUserAgent(userAgent: string) {
  const normalized = userAgent.toLowerCase();
  return AI_USER_AGENT_HINTS.some((token) => normalized.includes(token));
}

function resolveExternalActor(request: Request) {
  const headerActorId =
    request.headers.get("x-agent-id") ??
    request.headers.get("x-agent-name") ??
    request.headers.get("x-ai-agent-id") ??
    request.headers.get("x-ai-id");

  if (headerActorId) {
    return {
      actorType: "AGENT" as const,
      actorId: `agent:${normalizeActorId(headerActorId, "agent-client")}`,
    };
  }

  const userAgent = request.headers.get("user-agent") ?? "unknown";
  if (isLikelyAIAgentUserAgent(userAgent)) {
    return {
      actorType: "AGENT" as const,
      actorId: `agent:${normalizeActorId(userAgent, "agent")}`,
    };
  }

  return {
    actorType: "USER" as const,
    actorId: `open-tasks:${resolveSourceIp(request)}`,
  };
}

export async function GET(request: Request) {
  const sourceIp = resolveSourceIp(request);
  const isPublicIp = !isPrivateIp(sourceIp);
  const trafficAction = isPublicIp ? "EXTERNAL_LIST_OPEN_TASKS" : "INTERNAL_LIST_OPEN_TASKS";
  const trace = requestContext(request);

  try {
    const tasks = await prisma.task.findMany({
      where: {
        status: TaskStatus.OPEN,
        is_private: false,
        title: {
          not: {
            startsWith: "GitHub Issue:",
          },
        },
      },
      orderBy: [
        { is_priority: "desc" },
        { created_at: "desc" }
      ],
      select: {
        id: true,
        title: true,
        description: true,
        reward_amount: true,
        reward_currency: true,
        required_stack: true,
        status: true,
        difficulty: true,
        scope_clarity_score: true,
        created_at: true,
        updated_at: true,
        scout_id: true,
        stripe_checkout_session_id: true,
        stripe_payment_intent_id: true,
        is_priority: true,
      },
    });

    const publicPayload = tasks.map((task) => {
      const preview = getTaskPreview(task.description);
      
      return {
        task_id: task.id,
        title: task.title,
        description_preview: preview.description_preview,
        description_chars: preview.description_chars,
        has_clear_steps: preview.has_clear_steps,
        status: task.status,
        difficulty: task.difficulty,
        reward_amount_cents: task.reward_amount,
        reward_display: `$${(task.reward_amount / 100).toFixed(2)} ${task.reward_currency}`,
        required_stack: task.required_stack,
        scope_clarity_score: task.scope_clarity_score,
        created_at: task.created_at.toISOString(),
        updated_at: task.updated_at.toISOString(),
        source: task.scout_id ? "scout" : "human",
        payout_mode: getPayoutMode(task),
        is_priority: task.is_priority,
        task_url: `https://agent.wooo.work/tasks/${task.id}`,
      };
    });

    const conversionHints = {
      mcp_command: MCP_BOOTSTRAP_COMMAND,
      api_base_url: MCP_API_BASE_URL,
      demand_proposal_url: `${VIBEWORK_SITE_URL}/propose`,
      agent_growth_kit_url: `${AGENT_GATEWAY_URL}/api/a2a/growth/kit?agent_id=<YOUR_AGENT_ID>&register=true`,
      referral_url_template: `${VIBEWORK_SITE_URL}/propose?ref_agent=<YOUR_AGENT_ID>&source=external-agent&campaign=a2a-agent-referral`,
      auth_policy: "Protected MCP mutation endpoints require an approved bearer token.",
      protected_tools: ["agent_card", "claim_task", "submit_bid", "submit_solution"],
      payload_hints: [
        "task_id = 開放任務 UUID",
        "agent_id = 你的穩定識別碼（例如外部 agent name）",
        "developer_wallet = Stripe Connect acct_xxx 或 EVM 0x 地址；僅限核准後的 agent 使用",
        "ref_agent = 外部 agent referral id；帶到 /propose 後會進入 attribution 與 affiliate ledger",
      ],
      required_steps: [
        "1) 先用 curl 或 MCP 列出任務",
        "2) 註冊 agent card 並等待白名單核准",
        "3) 用 growth kit 將外部需求方導到 VibeWork paid intake",
        "4) 核准後再依平台規則 bid/claim/submit",
      ],
    };

    const actor = resolveExternalActor(request);

    void sendTrafficAlert({
      level: "info",
      action: trafficAction,
      surface: "public-open-tasks",
      actorType: actor.actorType,
      actorId: actor.actorId,
      taskId: "open-tasks",
      sourceIp,
      userAgent: request.headers.get("user-agent") ?? "unknown",
      message: `External discovery call for open tasks (${publicPayload.length} items)`,
      metadata: {
        ...trace,
        source: "public-open-tasks",
        task_count: publicPayload.length,
        task_ids: tasks.slice(0, 20).map((task) => task.id),
        source_ip: sourceIp,
        response_status: 200,
        response_summary: `open_tasks_ok:${publicPayload.length}`,
        auth_hint: isPublicIp ? "public" : "internal",
      },
    });

    // Light-weight surge signal: when this endpoint is hit in large bursts,
    // emit a warning once every 25 requests in a 10-minute window.
    const surgeWindow = 10;
    const surgeWindowStart = new Date(Date.now() - surgeWindow * 60 * 1000);
    void prisma.auditEvent.count({
      where: {
        createdAt: { gte: surgeWindowStart },
        action: trafficAction,
      },
    }).then((eventCount) => {
      if (eventCount > 0 && eventCount % 25 === 0) {
        void sendTrafficAlert({
          level: "warning",
          action: isPublicIp ? "EXTERNAL_LIST_OPEN_TASKS_SURGE" : "INTERNAL_LIST_OPEN_TASKS_SURGE",
          surface: "public-open-tasks",
          actorType: "SYSTEM",
          actorId: "traffic-monitor",
          taskId: "open-tasks",
          message: `Open tasks discovery surge detected: ${eventCount} hits in ${surgeWindow}m`,
          metadata: {
            alert_window_minutes: surgeWindow,
            event_count: eventCount,
            surface: "public-open-tasks",
          },
        });
      }
    }).catch(() => {});

    if (isPublicIp) {
      void evaluateExternalFunnelHealth({
        surface: "public-open-tasks",
        periodMinutes: 10,
      });
    }

    return NextResponse.json({
      platform: "VibeWork",
      version: "v1",
      discovery_mode: "ai-first",
      beta_program: "VibeWork A2A paid proposal intake + reviewed agent bounty routing",
      conversion_hints: conversionHints,
      tasks: publicPayload,
      total_open: publicPayload.length,
      request_id: trace.request_id,
      last_refreshed_at: new Date().toISOString(),
    });
  } catch (error: unknown) {
    console.error("[open-tasks] Internal error", error);

    const errorName = error instanceof Error ? error.name : "Error";
    const errorMessage = error instanceof Error ? error.message : "internal_error";

    const actor = resolveExternalActor(request);

    void sendTrafficAlert({
      level: "error",
      action: isPublicIp ? "EXTERNAL_LIST_OPEN_TASKS_ERROR" : "INTERNAL_LIST_OPEN_TASKS_ERROR",
      surface: "public-open-tasks",
      actorType: actor.actorType,
      actorId: actor.actorId,
      taskId: "open-tasks",
      sourceIp,
      userAgent: request.headers.get("user-agent") ?? "unknown",
      message: `open-tasks 查詢失敗: ${errorName}: ${errorMessage}`,
      metadata: {
        ...trace,
        source: "public-open-tasks",
        source_ip: sourceIp,
        response_status: 500,
        response_summary: "open_tasks_error",
        error_name: errorName,
        error_message: errorMessage,
      },
    });

    return NextResponse.json(
      { error_type: "InternalError", error: "Internal Server Error", request_id: trace.request_id },
      { status: 500 }
    );
  }
}
