import type { ContentMediaType } from "@/types/workflow";
import { buildContentPost, type CreateContentPostInput } from "./post-model";
import { parseHashtags } from "./manual-post";

export interface CsvImportRow {
  channel: string;
  destination?: string;
  mediaType: string;
  title?: string;
  caption: string;
  hashtags?: string;
  link?: string;
  cta?: string;
  image_url?: string;
  video_url?: string;
  audience_name?: string;
  status?: string;
}

export interface CsvImportResult {
  imported: number;
  errors: { row: number; message: string }[];
  posts: ReturnType<typeof buildContentPost>[];
}

const MAX_ROWS = 200;

function parseCsvLine(line: string): string[] {
  const fields: string[] = [];
  let current = "";
  let inQuotes = false;

  for (let i = 0; i < line.length; i++) {
    const ch = line[i]!;
    if (ch === '"') {
      if (inQuotes && line[i + 1] === '"') {
        current += '"';
        i++;
      } else {
        inQuotes = !inQuotes;
      }
    } else if (ch === "," && !inQuotes) {
      fields.push(current.trim());
      current = "";
    } else {
      current += ch;
    }
  }
  fields.push(current.trim());
  return fields;
}

function normalizeHeader(h: string): string {
  return h.trim().toLowerCase().replace(/\s+/g, "_");
}

export function parseCsvContent(csvText: string): { headers: string[]; rows: Record<string, string>[] } {
  const lines = csvText
    .replace(/^\uFEFF/, "")
    .split(/\r?\n/)
    .map((l) => l.trim())
    .filter(Boolean);

  if (lines.length < 2) {
    throw new Error("CSV must include a header row and at least one data row");
  }

  const headers = parseCsvLine(lines[0]!).map(normalizeHeader);
  const rows: Record<string, string>[] = [];

  for (let i = 1; i < lines.length; i++) {
    const values = parseCsvLine(lines[i]!);
    const row: Record<string, string> = {};
    headers.forEach((h, idx) => {
      row[h] = values[idx] ?? "";
    });
    rows.push(row);
  }

  return { headers, rows };
}

function rowToCsvImportRow(row: Record<string, string>): CsvImportRow {
  return {
    channel: row.channel ?? "",
    destination: row.destination,
    mediaType: row.mediatype ?? row.media_type ?? "content",
    title: row.title,
    caption: row.caption ?? row.text ?? "",
    hashtags: row.hashtags,
    link: row.link ?? row.link_url,
    cta: row.cta,
    image_url: row.image_url,
    video_url: row.video_url,
    audience_name: row.audience_name,
    status: row.status,
  };
}

function validateCsvRow(row: CsvImportRow, rowNum: number): string | null {
  if (!row.caption?.trim()) return `Row ${rowNum}: caption is required`;
  if (!row.channel?.trim()) return `Row ${rowNum}: channel is required`;
  const media = row.mediaType?.toLowerCase();
  if (!["content", "image", "video"].includes(media)) {
    return `Row ${rowNum}: mediaType must be content, image, or video`;
  }
  if (media === "image" && !row.image_url?.trim()) {
    return `Row ${rowNum}: image_url required when mediaType=image`;
  }
  if (media === "video" && !row.video_url?.trim()) {
    return `Row ${rowNum}: video_url required when mediaType=video`;
  }
  return null;
}

export function importCsvRows(
  csvText: string,
  userId: string,
  project: CreateContentPostInput["project"],
  brand: CreateContentPostInput["brand"],
  context?: CreateContentPostInput["context"],
): CsvImportResult {
  const { rows } = parseCsvContent(csvText);
  if (rows.length > MAX_ROWS) {
    throw new Error(`CSV exceeds maximum of ${MAX_ROWS} rows`);
  }

  const result: CsvImportResult = { imported: 0, errors: [], posts: [] };

  rows.forEach((raw, index) => {
    const rowNum = index + 2;
    const row = rowToCsvImportRow(raw);
    const err = validateCsvRow(row, rowNum);
    if (err) {
      result.errors.push({ row: rowNum, message: err });
      return;
    }

    const mediaType = row.mediaType.toLowerCase() as ContentMediaType;
    const post = buildContentPost({
      userId,
      project,
      brand,
      context,
      origin: "csv_import",
      title: row.title,
      caption: row.caption,
      hashtags: parseHashtags(row.hashtags),
      linkUrl: row.link,
      cta: row.cta,
      mediaType,
      platforms: [row.channel.toLowerCase()],
      imageUrl: row.image_url || null,
      videoUrl: row.video_url || null,
      status: "draft",
    });

    result.posts.push(post);
    result.imported++;
  });

  return result;
}

export const CSV_TEMPLATE = `channel,destination,mediaType,title,caption,hashtags,link,cta,image_url,video_url,audience_name,status
linkedin,account,content,Launch update,"Your caption here","Launch;Product",https://example.com,Learn more,,,,
facebook,page,image,Product highlight,"Caption for image post","Brand;Launch",,,https://example.com/image.png,,,draft`;
