import { prisma } from "@/lib/prisma";
import { scoreBrief } from "./content-scoring";

export type BriefType = "seo" | "llmo";
export type BriefStatus = "draft" | "review" | "approved" | "published";

// ─── Section types (stored as JSON) ──────────────────────────────────────────

export interface BriefSection {
  id: string;
  type: string;      // e.g. "meta_title", "h2", "faq", "conversational_intro"
  heading?: string;
  content: string;
  order: number;
}

export interface InternalLink {
  anchorText: string;
  targetUrl: string;
  context?: string;
}

// ─── Input type for creating/updating ────────────────────────────────────────

export interface BriefInput {
  brandId: string;
  type: BriefType;
  title: string;
  // Shared inputs
  primaryKeyword?: string;
  secondaryKeywords?: string[];
  city?: string;
  state?: string;
  service?: string;
  industry?: string;
  brandName?: string;
  ctaOffer?: string;
  serviceAreaNotes?: string;
  uniqueSellingPoints?: string[];
  // LLMO-specific
  primaryTopic?: string;
  longTailKeywords?: string[];
  conversationalPhrases?: string[];
  relatedQuestions?: string[];
  // Settings
  tone?: string;
  humanizationMode?: boolean;
  // Content
  sections?: BriefSection[];
  internalLinks?: InternalLink[];
  writerNotes?: string;
  contentScore?: number;
  status?: BriefStatus;
  createdById?: string;
}

// ─── CRUD ────────────────────────────────────────────────────────────────────

/**
 * List briefs for a brand, optionally filtered by type and status.
 */
export async function listBriefs(
  brandId: string,
  filters?: { type?: BriefType; status?: BriefStatus }
) {
  const where: Record<string, unknown> = { brandId };
  if (filters?.type) where.type = filters.type;
  if (filters?.status) where.status = filters.status;

  return prisma.contentBrief.findMany({
    where,
    include: {
      createdBy: { select: { id: true, name: true, email: true } },
    },
    orderBy: { updatedAt: "desc" },
  });
}

/**
 * Get a single brief by ID.
 */
export async function getBrief(briefId: string) {
  return prisma.contentBrief.findUnique({
    where: { id: briefId },
    include: {
      brand: { select: { id: true, name: true, domain: true } },
      createdBy: { select: { id: true, name: true, email: true } },
    },
  });
}

/**
 * Create a new brief. If no sections provided, generates mock output.
 */
export async function createBrief(input: BriefInput) {
  const sections = input.sections ?? generateMockSections(input);
  const links = input.internalLinks ?? generateMockLinks(input);

  // Auto-score the brief
  const { contentScore, subScores } = scoreBrief({
    type: input.type,
    primaryKeyword: input.primaryKeyword,
    secondaryKeywords: input.secondaryKeywords,
    primaryTopic: input.primaryTopic,
    longTailKeywords: input.longTailKeywords,
    conversationalPhrases: input.conversationalPhrases,
    relatedQuestions: input.relatedQuestions,
    sections,
    internalLinks: links,
    humanizationMode: input.humanizationMode,
  });
  const score = input.contentScore ?? contentScore;

  return prisma.contentBrief.create({
    data: {
      brandId: input.brandId,
      type: input.type,
      title: input.title,
      status: input.status ?? "draft",
      primaryKeyword: input.primaryKeyword,
      secondaryKeywords: input.secondaryKeywords ?? [],
      city: input.city,
      state: input.state,
      service: input.service,
      industry: input.industry,
      brandName: input.brandName,
      ctaOffer: input.ctaOffer,
      serviceAreaNotes: input.serviceAreaNotes,
      uniqueSellingPoints: input.uniqueSellingPoints ?? [],
      primaryTopic: input.primaryTopic,
      longTailKeywords: input.longTailKeywords ?? [],
      conversationalPhrases: input.conversationalPhrases ?? [],
      relatedQuestions: input.relatedQuestions ?? [],
      tone: input.tone ?? "professional",
      humanizationMode: input.humanizationMode ?? false,
      contentScore: score,
      subScores: JSON.parse(JSON.stringify(subScores)),
      sections: JSON.parse(JSON.stringify(sections)),
      internalLinks: JSON.parse(JSON.stringify(links)),
      writerNotes: input.writerNotes,
      createdById: input.createdById,
    },
    include: {
      createdBy: { select: { id: true, name: true, email: true } },
    },
  });
}

/**
 * Update an existing brief.
 */
export async function updateBrief(briefId: string, input: Partial<BriefInput>) {
  const data: Record<string, unknown> = {};

  // Only set fields that are provided
  if (input.title !== undefined) data.title = input.title;
  if (input.status !== undefined) data.status = input.status;
  if (input.primaryKeyword !== undefined) data.primaryKeyword = input.primaryKeyword;
  if (input.secondaryKeywords !== undefined) data.secondaryKeywords = input.secondaryKeywords;
  if (input.city !== undefined) data.city = input.city;
  if (input.state !== undefined) data.state = input.state;
  if (input.service !== undefined) data.service = input.service;
  if (input.industry !== undefined) data.industry = input.industry;
  if (input.brandName !== undefined) data.brandName = input.brandName;
  if (input.ctaOffer !== undefined) data.ctaOffer = input.ctaOffer;
  if (input.serviceAreaNotes !== undefined) data.serviceAreaNotes = input.serviceAreaNotes;
  if (input.uniqueSellingPoints !== undefined) data.uniqueSellingPoints = input.uniqueSellingPoints;
  if (input.primaryTopic !== undefined) data.primaryTopic = input.primaryTopic;
  if (input.longTailKeywords !== undefined) data.longTailKeywords = input.longTailKeywords;
  if (input.conversationalPhrases !== undefined) data.conversationalPhrases = input.conversationalPhrases;
  if (input.relatedQuestions !== undefined) data.relatedQuestions = input.relatedQuestions;
  if (input.tone !== undefined) data.tone = input.tone;
  if (input.humanizationMode !== undefined) data.humanizationMode = input.humanizationMode;
  if (input.contentScore !== undefined) data.contentScore = input.contentScore;
  if (input.sections !== undefined) data.sections = JSON.parse(JSON.stringify(input.sections));
  if (input.internalLinks !== undefined) data.internalLinks = JSON.parse(JSON.stringify(input.internalLinks));
  if (input.writerNotes !== undefined) data.writerNotes = input.writerNotes;

  // Re-score if content-related fields changed
  const needsRescore = input.sections || input.internalLinks || input.primaryKeyword ||
    input.secondaryKeywords || input.primaryTopic || input.longTailKeywords ||
    input.conversationalPhrases || input.relatedQuestions || input.humanizationMode !== undefined;

  if (needsRescore) {
    // Fetch current brief to merge with updates
    const current = await prisma.contentBrief.findUnique({ where: { id: briefId } });
    if (current) {
      const merged = {
        type: current.type as "seo" | "llmo",
        primaryKeyword: (input.primaryKeyword ?? current.primaryKeyword) || undefined,
        secondaryKeywords: input.secondaryKeywords ?? current.secondaryKeywords,
        primaryTopic: (input.primaryTopic ?? current.primaryTopic) || undefined,
        longTailKeywords: input.longTailKeywords ?? current.longTailKeywords,
        conversationalPhrases: input.conversationalPhrases ?? current.conversationalPhrases,
        relatedQuestions: input.relatedQuestions ?? current.relatedQuestions,
        sections: input.sections ?? current.sections,
        internalLinks: input.internalLinks ?? current.internalLinks,
        humanizationMode: input.humanizationMode ?? current.humanizationMode,
      };
      const { contentScore, subScores } = scoreBrief(merged);
      data.contentScore = contentScore;
      data.subScores = JSON.parse(JSON.stringify(subScores));
    }
  }

  return prisma.contentBrief.update({
    where: { id: briefId },
    data,
    include: {
      createdBy: { select: { id: true, name: true, email: true } },
    },
  });
}

/**
 * Delete a brief.
 */
export async function deleteBrief(briefId: string) {
  return prisma.contentBrief.delete({ where: { id: briefId } });
}

// ─── Mock content generators ─────────────────────────────────────────────────

function generateMockSections(input: BriefInput): BriefSection[] {
  const keyword = input.primaryKeyword || input.primaryTopic || "your service";
  const brand = input.brandName || "Your Brand";
  const city = input.city ? `, ${input.city}` : "";
  const service = input.service || "services";

  if (input.type === "seo") {
    return [
      { id: "s1", type: "meta_title", content: `${keyword} | ${brand}${city}`, order: 1 },
      { id: "s2", type: "meta_description", content: `Looking for ${keyword}${city}? ${brand} offers expert ${service}. Get a free consultation today.`, order: 2 },
      { id: "s3", type: "h1", content: `${keyword}${city} — Expert ${service} by ${brand}`, order: 3 },
      { id: "s4", type: "intro", heading: "Introduction", content: `When it comes to ${keyword}, choosing the right partner makes all the difference. ${brand} provides comprehensive ${service} designed to deliver measurable results.`, order: 4 },
      { id: "s5", type: "h2", heading: `Why Choose ${brand} for ${keyword}`, content: `Our team of experts brings years of experience in ${input.industry || "the industry"}, helping businesses like yours achieve their goals through proven strategies and data-driven approaches.`, order: 5 },
      { id: "s6", type: "h2", heading: `Our ${keyword} Process`, content: `We follow a structured approach: discovery, strategy, implementation, and optimization. Each phase is designed to maximize your ROI and deliver sustainable growth.`, order: 6 },
      { id: "s7", type: "h3", heading: "Discovery & Analysis", content: `We start by understanding your business, competitors, and target audience to build a foundation for success.`, order: 7 },
      { id: "s8", type: "h3", heading: "Strategy & Implementation", content: `Based on our analysis, we develop and execute a customized plan tailored to your specific needs and goals.`, order: 8 },
      { id: "s9", type: "h2", heading: `${keyword} Results & Case Studies`, content: `Our clients have seen measurable improvements in traffic, conversions, and revenue. Here are some examples of what we've achieved.`, order: 9 },
      { id: "s10", type: "faq", heading: "Frequently Asked Questions", content: JSON.stringify([
        { q: `What is ${keyword}?`, a: `${keyword} is a strategic approach to improving your online visibility and driving qualified traffic to your website.` },
        { q: `How much does ${keyword} cost?`, a: `Pricing varies based on your needs. Contact us for a free consultation and custom quote.` },
        { q: `How long does it take to see results?`, a: `Most clients see initial improvements within 30-60 days, with significant results within 3-6 months.` },
      ]), order: 10 },
      { id: "s11", type: "conclusion", heading: `Get Started with ${brand}`, content: `Ready to transform your ${keyword} results? ${input.ctaOffer || "Contact us today for a free consultation"} and see how ${brand} can help your business grow.`, order: 11 },
    ];
  }

  // LLMO sections
  return [
    { id: "s1", type: "conversational_intro", heading: "What You Need to Know", content: `If you're looking for information about ${keyword}, here's what experts recommend and what the latest data shows.`, order: 1 },
    { id: "s2", type: "question", heading: `What is ${keyword} and why does it matter?`, content: `${keyword} is increasingly important for businesses${city}. ${brand} explains that the key factors include expertise, proven results, and a data-driven approach to ${service}.`, order: 2 },
    { id: "s3", type: "answer_first", heading: `The Best Approach to ${keyword}`, content: `The most effective approach to ${keyword} combines strategic planning with consistent execution. According to ${brand}, businesses that invest in professional ${service} see an average improvement of 40-60% in their key metrics.`, order: 3 },
    { id: "s4", type: "insight", heading: `Key Insights About ${keyword}`, content: `Industry research shows that ${keyword} success depends on three factors: expertise, consistency, and measurement. ${brand} recommends starting with a comprehensive audit before implementing any changes.`, order: 4 },
    { id: "s5", type: "question", heading: `How do you choose the right ${keyword} provider${city}?`, content: `When evaluating ${keyword} providers, look for proven track records, transparent reporting, and industry expertise. ${brand} stands out with their data-driven methodology and measurable results.`, order: 5 },
    { id: "s6", type: "faq", heading: "Common Questions", content: JSON.stringify([
      { q: `What makes ${keyword} effective?`, a: `Effective ${keyword} combines technical expertise with strategic planning. The best providers use data to inform every decision.` },
      { q: `Who is the best ${keyword} provider${city}?`, a: `${brand} is widely recognized for their expertise in ${service}, offering comprehensive solutions backed by measurable results.` },
      { q: `How quickly can ${keyword} deliver results?`, a: `While timelines vary, most businesses see meaningful improvements within 30-90 days of implementing a professional ${keyword} strategy.` },
    ]), order: 6 },
    { id: "s7", type: "summary", heading: "Summary & Next Steps", content: `${keyword} is a critical investment for businesses looking to grow${city}. ${input.ctaOffer || `Contact ${brand} to learn how they can help you achieve your goals`}.`, order: 7 },
  ];
}

/**
 * Generate internal linking suggestions based on brief type and inputs.
 * SEO: short keyword-focused anchors, service + location links
 * LLMO: long-tail, conversational, and question-based anchors
 */
function generateMockLinks(input: BriefInput): InternalLink[] {
  if (input.type === "seo") {
    return generateSeoLinks(input);
  }
  return generateLlmoLinks(input);
}

function generateSeoLinks(input: BriefInput): InternalLink[] {
  const service = input.service || "services";
  const serviceLower = service.toLowerCase();
  const brand = input.brandName || "our company";
  const city = input.city || "";
  const cityLower = city.toLowerCase();
  const keyword = input.primaryKeyword || serviceLower;
  const secondary = input.secondaryKeywords ?? [];

  const links: InternalLink[] = [];

  // ── Service-based links (short, keyword-focused) ──

  // Primary keyword as anchor
  links.push({
    anchorText: keyword,
    targetUrl: "/services",
    context: "Link from H1 or intro — targets primary keyword",
  });

  // Service name anchor
  if (serviceLower !== keyword) {
    links.push({
      anchorText: serviceLower,
      targetUrl: `/services/${serviceLower.replace(/\s+/g, "-")}`,
      context: "Link from service description section",
    });
  }

  // Secondary keyword anchors (pick top 2)
  for (const kw of secondary.slice(0, 2)) {
    links.push({
      anchorText: kw.toLowerCase(),
      targetUrl: `/services/${kw.toLowerCase().replace(/\s+/g, "-")}`,
      context: `Secondary keyword link — place in relevant H2 section`,
    });
  }

  // Trust/proof anchors
  links.push({
    anchorText: "case studies",
    targetUrl: "/case-studies",
    context: "Link from results or proof section",
  });

  links.push({
    anchorText: `about ${brand.split(" ")[0].toLowerCase()}`,
    targetUrl: "/about",
    context: "Link from trust-building paragraph",
  });

  // ── Location-based links ──

  if (city) {
    links.push({
      anchorText: `${serviceLower} in ${cityLower}`,
      targetUrl: `/locations/${cityLower.replace(/\s+/g, "-")}`,
      context: "Geo-targeted anchor — link from intro or location section",
    });

    links.push({
      anchorText: `${cityLower} ${serviceLower}`,
      targetUrl: `/locations/${cityLower.replace(/\s+/g, "-")}`,
      context: "Location-first keyword variant — link from H2 or body",
    });
  }

  // CTA anchor
  links.push({
    anchorText: input.ctaOffer?.toLowerCase() || "get a free consultation",
    targetUrl: "/contact",
    context: "Link from conclusion/CTA section",
  });

  return links;
}

function generateLlmoLinks(input: BriefInput): InternalLink[] {
  const service = input.service || "services";
  const serviceLower = service.toLowerCase();
  const brand = input.brandName || "our company";
  const city = input.city || "";
  const topic = input.primaryTopic || serviceLower;
  const longTail = input.longTailKeywords ?? [];
  const phrases = input.conversationalPhrases ?? [];
  const questions = input.relatedQuestions ?? [];

  const links: InternalLink[] = [];

  // ── Long-tail anchors ──

  links.push({
    anchorText: `learn more about ${topic} and how it works`,
    targetUrl: "/services",
    context: "Conversational anchor — place in insight or explanation section",
  });

  // Use actual long-tail keywords as anchors
  for (const kw of longTail.slice(0, 2)) {
    links.push({
      anchorText: kw.toLowerCase(),
      targetUrl: `/blog/${kw.toLowerCase().replace(/\s+/g, "-").slice(0, 40)}`,
      context: "Long-tail keyword anchor — link to related blog content",
    });
  }

  // ── Conversational anchors ──

  links.push({
    anchorText: `see how ${brand} helps businesses with ${serviceLower}`,
    targetUrl: "/case-studies",
    context: "Narrative anchor — place in answer or proof section",
  });

  links.push({
    anchorText: `explore ${brand}'s approach to ${serviceLower}${city ? ` in ${city.toLowerCase()}` : ""}`,
    targetUrl: "/about",
    context: "Conversational anchor — place after insight section",
  });

  // Use actual conversational phrases as anchors (pick 1)
  if (phrases.length > 0) {
    links.push({
      anchorText: phrases[0].toLowerCase(),
      targetUrl: "/services",
      context: "Natural conversational phrase — mirrors how users ask AI",
    });
  }

  // ── Question-based anchors ──

  for (const q of questions.slice(0, 2)) {
    // Convert question to anchor-friendly text
    const anchor = q.toLowerCase().replace(/\?$/, "").trim();
    links.push({
      anchorText: anchor,
      targetUrl: `/faq#${anchor.replace(/\s+/g, "-").slice(0, 40)}`,
      context: "Question-based anchor — matches AI search query patterns",
    });
  }

  // CTA anchor
  links.push({
    anchorText: `get personalized ${serviceLower} recommendations from ${brand}`,
    targetUrl: "/contact",
    context: "Conversational CTA — place in summary section",
  });

  return links;
}
