/**
 * POST /api/backlinks/acquisition-strategy
 *
 * Generates an AI acquisition plan for a specific backlink gap domain.
 * Body: { brandId, domain, difficulty?, competitorBacklinks? }
 * Returns: { steps: Array<{title, action, effort, linkType, dofollow}>,
 *   difficultyExplanation: string, estimatedImpact: string }
 *
 * Cached 24h per (brandId, domain).
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { callLlm } from "@/lib/ai-avatar/llm-client";

export const dynamic = "force-dynamic";
export const maxDuration = 30;

interface Step {
  title: string;
  action: string;
  effort: string;
  linkType: string;
  dofollow: boolean;
}

interface StrategyResponse {
  steps: Step[];
  difficultyExplanation: string;
  estimatedImpact: string;
  cached?: boolean;
}

const CACHE_TTL = 24 * 60 * 60 * 1000;
const cache = new Map<string, { data: StrategyResponse; ts: number }>();

const FALLBACK: StrategyResponse = {
  steps: [{
    title: "Research the domain",
    action: "Visit the domain to understand what kind of backlinks it provides (directory, editorial, profile, etc.) and identify the right path to acquire one.",
    effort: "30 minutes",
    linkType: "varies",
    dofollow: true,
  }],
  difficultyExplanation: "AI couldn't generate a specific strategy. Review the domain manually to assess acquisition difficulty.",
  estimatedImpact: "Acquiring a backlink from a high-authority domain typically improves overall domain authority and search visibility.",
};

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null) as {
    brandId?: string;
    domain?: string;
    difficulty?: string;
    competitorBacklinks?: string[];
  } | null;

  if (!body?.brandId || !body?.domain) {
    return NextResponse.json({ error: "brandId and domain required" }, { status: 400 });
  }

  const brand = await prisma.brand.findUnique({
    where: { id: body.brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const cacheKey = `${body.brandId}:${body.domain}`;
  const cached = cache.get(cacheKey);
  if (cached && Date.now() - cached.ts < CACHE_TTL) {
    return NextResponse.json({ ...cached.data, cached: true });
  }

  const sys = `You are an SEO + link-building expert. The user wants to acquire a backlink from a specific domain. Generate 3-5 specific, actionable steps in JSON format.

Return ONLY valid JSON in this shape (no markdown, no commentary):
{
  "difficultyExplanation": "1-2 sentence explanation of WHY this difficulty rating (Easy/Medium/Hard) — what makes this domain easy or hard to get a link from",
  "estimatedImpact": "1 sentence forecast of expected SEO impact if a backlink is acquired",
  "steps": [
    {
      "title": "Short imperative title",
      "action": "Specific action: include URLs to visit, forms to fill, or content to create. Be concrete, not generic.",
      "effort": "Time estimate (e.g. '15 minutes', '2 hours', '1 day')",
      "linkType": "directory | profile | editorial | guest_post | resource_listing | citation | press | review",
      "dofollow": true | false
    }
  ]
}`;

  const compInfo = body.competitorBacklinks && body.competitorBacklinks.length > 0
    ? `\nCompetitor's backlinks from this domain (for reference):\n${body.competitorBacklinks.slice(0, 5).map((u) => `- ${u}`).join("\n")}`
    : "";

  const userMsg = `Brand: ${brand.name} (${brand.domain})
Industry: ${brand.industry ?? "unknown"}
Target backlink source domain: ${body.domain}
Difficulty rating: ${body.difficulty ?? "unknown"}${compInfo}

Generate the acquisition strategy.`;

  let result: StrategyResponse;
  try {
    const llm = await callLlm(
      [
        { role: "system", content: sys },
        { role: "user", content: userMsg },
      ],
      () => JSON.stringify(FALLBACK),
      { maxTokens: 1500 },
    );

    let text = llm.reply.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "");
    const f = text.indexOf("{"), l = text.lastIndexOf("}");
    if (f >= 0 && l > f) text = text.slice(f, l + 1);
    const parsed = JSON.parse(text) as Partial<StrategyResponse>;

    result = {
      steps: Array.isArray(parsed.steps) ? parsed.steps.slice(0, 5).map((s) => ({
        title: typeof s.title === "string" ? s.title.slice(0, 200) : "Action step",
        action: typeof s.action === "string" ? s.action.slice(0, 1000) : "",
        effort: typeof s.effort === "string" ? s.effort.slice(0, 50) : "varies",
        linkType: typeof s.linkType === "string" ? s.linkType.slice(0, 50) : "varies",
        dofollow: typeof s.dofollow === "boolean" ? s.dofollow : true,
      })) : FALLBACK.steps,
      difficultyExplanation: typeof parsed.difficultyExplanation === "string"
        ? parsed.difficultyExplanation.slice(0, 500)
        : FALLBACK.difficultyExplanation,
      estimatedImpact: typeof parsed.estimatedImpact === "string"
        ? parsed.estimatedImpact.slice(0, 500)
        : FALLBACK.estimatedImpact,
    };
  } catch (err) {
    console.error("[backlinks/acquisition-strategy] LLM failed:", err instanceof Error ? err.message : err);
    result = FALLBACK;
  }

  cache.set(cacheKey, { data: result, ts: Date.now() });
  return NextResponse.json(result);
}
