import type { MarketingPlan, ChannelStrategyCard, ContentPillar, AssetCard, YouTubeRepurposeItem } from '@/features/plan/types/plan';
import type { EnrichmentData } from '@/features/report/lib/transformReport';
import { generateContentPlan } from '@/features/studio/lib/contentDirector';

/**
 * Supabase marketing_reports 테이블의 원본 report 데이터.
 * `report` JSONB에는 AI 생성 분석 결과가 포함됨.
 */
interface RawReportRow {
  id: string;
  url: string;
  clinic_name: string;
  report: Record<string, unknown>;
  scrape_data?: Record<string, unknown>;
  analysis_data?: Record<string, unknown>;
  created_at: string;
}

const CHANNEL_NAME_MAP: Record<string, string> = {
  naverBlog: '네이버 블로그',
  naverPlace: '네이버 플레이스',
  gangnamUnni: '강남언니',
  instagram: 'Instagram',
  youtube: 'YouTube',
  facebook: 'Facebook',
  website: '웹사이트',
  tiktok: 'TikTok',
};

const CHANNEL_ICON_MAP: Record<string, string> = {
  naverBlog: 'blog',
  instagram: 'instagram',
  youtube: 'youtube',
  facebook: 'facebook',
  naverPlace: 'map',
  gangnamUnni: 'star',
  website: 'globe',
  tiktok: 'video',
};

// 채널별 톤 매트릭스 (Audit C3)
const CHANNEL_TONE_MAP: Record<string, string> = {
  youtube: '교육적 · 권위 (Long) / 캐주얼 · 후킹 (Shorts)',
  instagram: '트렌디 · 공감 (Reel) / 감성적 · 프리미엄 (Feed)',
  naverBlog: '정보성 · SEO 최적화',
  gangnamUnni: '전문 · 응대 · 신뢰',
  facebook: '타겟팅 · CTA 중심',
  tiktok: '밈 · 교육 · MZ세대',
  naverPlace: '정보성 · 지역 SEO',
  website: '브랜드 · 프리미엄',
};

function buildChannelStrategies(
  channelAnalysis: Record<string, Record<string, unknown>> | undefined,
  recommendations: Record<string, unknown>[] | undefined,
): ChannelStrategyCard[] {
  if (!channelAnalysis) return [];

  return Object.entries(channelAnalysis).map(([key, ch], i) => {
    const score = (ch.score as number) ?? 0;
    const relatedRecs = (recommendations || [])
      .filter(r => {
        const cat = ((r.category as string) || '').toLowerCase();
        return cat.includes(key.toLowerCase()) || cat.includes(CHANNEL_NAME_MAP[key]?.toLowerCase() || '');
      })
      .map(r => (r.title as string) || (r.description as string) || '');

    return {
      channelId: key,
      channelName: CHANNEL_NAME_MAP[key] || key,
      icon: CHANNEL_ICON_MAP[key] || 'globe',
      currentStatus: `점수: ${score}/100 (${(ch.status as string) || 'unknown'})`,
      targetGoal: (ch.recommendation as string) || '',
      contentTypes: relatedRecs.length > 0 ? relatedRecs : ['콘텐츠 전략 수립 필요'],
      postingFrequency: score >= 80 ? '주 3-5회' : score >= 60 ? '주 2-3회' : '주 1-2회 (시작)',
      tone: CHANNEL_TONE_MAP[key] || '전문적 · 친근한',
      formatGuidelines: [],
      priority: (score < 50 ? 'P0' : score < 70 ? 'P1' : 'P2') as 'P0' | 'P1' | 'P2',
    };
  });
}

function buildContentPillars(
  recommendations: Record<string, unknown>[] | undefined,
  services: string[] | undefined,
): ContentPillar[] {
  const PILLAR_COLORS = ['#6C5CE7', '#E17055', '#00B894', '#FDCB6E', '#0984E3'];
  const pillars: ContentPillar[] = [
    {
      title: '전문성 · 신뢰',
      description: '의료진 소개, 수술 과정, 인증/자격, 학회 발표, 해외 연수 콘텐츠로 신뢰 구축',
      relatedUsp: '전문 의료진',
      exampleTopics: services?.slice(0, 3).map(s => `${s} 시술 과정 소개`) || ['시술 과정 소개'],
      color: PILLAR_COLORS[0],
    },
    {
      title: '비포 · 애프터',
      description: '실제 환자 사례, 수술 전후 비교, 3D 시뮬레이션, 시간별 변화 기록으로 결과 시각화',
      relatedUsp: '검증된 결과',
      exampleTopics: services?.slice(0, 3).map(s => `${s} 비포/애프터`) || ['비포/애프터 사례'],
      color: PILLAR_COLORS[1],
    },
    {
      title: '환자 후기 · 리뷰',
      description: '실제 환자 인터뷰, 후기 콘텐츠, 강남언니 리뷰 관리로 사회적 증거 확보',
      relatedUsp: '환자 만족도',
      exampleTopics: ['환자 인터뷰 영상', '리뷰 하이라이트', '회복 일기'],
      color: PILLAR_COLORS[2],
    },
    {
      title: '트렌드 · 교육',
      description: '시술 트렌드, Q&A, 의학 정보, 비용 가이드로 잠재 고객 유입',
      relatedUsp: '최신 트렌드',
      exampleTopics: ['자주 묻는 질문 Q&A', '시술별 비용 가이드', '최신 성형 트렌드'],
      color: PILLAR_COLORS[3],
    },
    {
      title: '안전 · 케어',
      description: '수술 후 관리, 24시간 모니터링, 전담 간호사, 리커버리 프로그램으로 프리미엄 케어 차별화',
      relatedUsp: '프리미엄 안전 관리',
      exampleTopics: ['수술 후 48시간 집중 케어', '전담 간호사 1:1 관리', '응급 대응 프로토콜'],
      color: PILLAR_COLORS[4],
    },
  ];

  return pillars;
}

/**
 * 캘린더 빌드는 이제 Content Director 엔진에 위임됨.
 * 채널, 필러, 서비스, 기존 에셋을 기반으로 풍부한 4주 에디토리얼 플랜을 생성.
 */
function buildCalendar(
  channels: ChannelStrategyCard[],
  pillars: ContentPillar[],
  services: string[],
  enrichment: EnrichmentData | undefined,
  clinicName: string,
  report?: Record<string, unknown>,
) {
  // 재활용 제안용 YouTube 인기 영상 추출
  const youtubeVideos = enrichment?.youtube?.videos?.map(v => ({
    title: v.title || '',
    views: v.views || 0,
    type: ((v.duration && parseInt(v.duration) < 60) ? 'Short' : 'Long') as 'Short' | 'Long',
  }));

  // 토픽 생성용 report 키워드 추출 (Audit C5)
  const reportKeywords = report?.keywords as { primary?: { keyword: string; monthlySearches?: number }[] } | undefined;
  const keywords = reportKeywords?.primary;

  // 전략 기반 토픽용 강남언니 데이터 추출 (Audit C1)
  const guData = enrichment?.gangnamUnni as { rating?: number; totalReviews?: number; doctors?: { name: string }[] } | undefined;
  const gangnamUnniData = guData ? {
    rating: guData.rating,
    reviews: guData.totalReviews,
    doctors: guData.doctors?.length,
  } : undefined;

  return generateContentPlan({
    channels,
    pillars,
    services,
    youtubeVideos,
    clinicName,
    keywords,
    gangnamUnniData,
  });
}

function buildAssets(enrichment: EnrichmentData | undefined): { assets: AssetCard[]; youtubeRepurpose: YouTubeRepurposeItem[] } {
  if (!enrichment) return { assets: [], youtubeRepurpose: [] };

  const assets: AssetCard[] = [];
  let assetIdx = 0;

  // YouTube 영상 → 영상 에셋
  if (enrichment.youtube?.videos) {
    for (const v of enrichment.youtube.videos.slice(0, 5)) {
      assets.push({
        id: `yt-${assetIdx++}`,
        source: 'youtube',
        sourceLabel: 'YouTube',
        type: 'video',
        title: v.title || '영상',
        description: `조회수 ${(v.views || 0).toLocaleString()} · 좋아요 ${(v.likes || 0).toLocaleString()}`,
        repurposingSuggestions: ['Shorts 추출', '블로그 스크립트', '카드뉴스'],
        status: 'collected',
      });
    }
  }

  // Instagram 게시물 → 사진 에셋
  const igAccounts = enrichment.instagramAccounts || (enrichment.instagram ? [enrichment.instagram] : []);
  for (const ig of igAccounts) {
    if (ig.latestPosts) {
      for (const p of (ig.latestPosts as { type?: string; likes?: number; caption?: string }[]).slice(0, 3)) {
        assets.push({
          id: `ig-${assetIdx++}`,
          source: 'social',
          sourceLabel: `Instagram @${ig.username || ''}`,
          type: 'photo',
          title: (p.caption || '').slice(0, 60) || 'Instagram 게시물',
          description: `좋아요 ${(p.likes || 0).toLocaleString()}`,
          repurposingSuggestions: ['피드 리포스트', '스토리 하이라이트'],
          status: 'collected',
        });
      }
    }
  }

  // 네이버 블로그 게시물 → 텍스트 에셋
  if (enrichment.naverBlog?.posts) {
    for (const post of enrichment.naverBlog.posts.slice(0, 3)) {
      assets.push({
        id: `nb-${assetIdx++}`,
        source: 'blog',
        sourceLabel: '네이버 블로그',
        type: 'text',
        title: post.title || '블로그 포스트',
        description: post.description || '',
        repurposingSuggestions: ['SNS 카드뉴스', '영상 스크립트'],
        status: 'collected',
      });
    }
  }

  // YouTube 재활용 항목
  const youtubeRepurpose: YouTubeRepurposeItem[] = (enrichment.youtube?.videos || [])
    .slice(0, 5)
    .map(v => ({
      title: v.title || '',
      views: v.views || 0,
      type: ((v.duration && parseInt(v.duration) < 60) ? 'Short' : 'Long') as 'Short' | 'Long',
      repurposeAs: ['Shorts 3개 추출', '블로그 포스트 변환', '카드뉴스 4장', '카카오톡 CTA'],
    }));

  return { assets, youtubeRepurpose };
}

function buildChannelBrandingFromEnrichment(enrichment: EnrichmentData | undefined) {
  if (!enrichment) return [];

  const rules: { channel: string; icon: string; profilePhoto: string; bannerSpec: string; bioTemplate: string; currentStatus: 'correct' | 'incorrect' | 'missing' }[] = [];

  if (enrichment.youtube) {
    rules.push({
      channel: 'YouTube',
      icon: 'youtube',
      profilePhoto: enrichment.youtube.thumbnailUrl || '',
      bannerSpec: '2560×1440px 배너',
      bioTemplate: enrichment.youtube.description?.slice(0, 200) || '',
      currentStatus: enrichment.youtube.description ? 'correct' : 'missing',
    });
  }

  const igAccounts = enrichment.instagramAccounts || (enrichment.instagram ? [enrichment.instagram] : []);
  for (const ig of igAccounts) {
    rules.push({
      channel: `Instagram @${ig.username || ''}`,
      icon: 'instagram',
      profilePhoto: '',
      bannerSpec: 'N/A (하이라이트 커버)',
      bioTemplate: ig.bio || '',
      currentStatus: ig.bio ? 'correct' : 'missing',
    });
  }

  if (enrichment.facebook) {
    rules.push({
      channel: 'Facebook',
      icon: 'facebook',
      profilePhoto: enrichment.facebook.profilePictureUrl || '',
      bannerSpec: '820×312px 커버 사진',
      bioTemplate: enrichment.facebook.intro || '',
      currentStatus: enrichment.facebook.intro ? 'correct' : 'missing',
    });
  }

  return rules;
}

function buildBrandInconsistencies(enrichment: EnrichmentData | undefined, clinicName: string): { field: string; values: { channel: string; value: string; isCorrect: boolean }[]; impact: string; recommendation: string }[] {
  if (!enrichment) return [];
  const items: { field: string; values: { channel: string; value: string; isCorrect: boolean }[]; impact: string; recommendation: string }[] = [];

  // 채널별 이름 수집
  const names: { channel: string; value: string }[] = [];
  if (clinicName) names.push({ channel: '웹사이트', value: clinicName });
  if (enrichment.youtube?.channelName) names.push({ channel: 'YouTube', value: enrichment.youtube.channelName });
  const igAccounts = enrichment.instagramAccounts || (enrichment.instagram ? [enrichment.instagram] : []);
  for (const ig of igAccounts) {
    if (ig.username) names.push({ channel: `Instagram @${ig.username}`, value: ig.username });
  }
  if (enrichment.facebook?.pageName) names.push({ channel: 'Facebook', value: enrichment.facebook.pageName });
  if (enrichment.gangnamUnni?.name) names.push({ channel: '강남언니', value: enrichment.gangnamUnni.name });

  if (names.length >= 2) {
    const websiteName = names[0].value;
    items.push({
      field: '병원명',
      values: names.map(n => ({ channel: n.channel, value: n.value, isCorrect: n.value.toLowerCase().includes(websiteName.toLowerCase().slice(0, 4)) })),
      impact: '채널마다 다른 이름은 브랜드 인지도를 분산시킵니다',
      recommendation: '모든 채널에서 동일한 공식 병원명을 사용하세요',
    });
  }

  // 전화번호 수집
  const phones: { channel: string; value: string }[] = [];
  if (enrichment.googleMaps?.phone) phones.push({ channel: 'Google Maps', value: enrichment.googleMaps.phone as string });
  if (enrichment.naverPlace?.telephone) phones.push({ channel: '네이버 플레이스', value: enrichment.naverPlace.telephone });
  if (enrichment.facebook?.phone) phones.push({ channel: 'Facebook', value: enrichment.facebook.phone as string });
  if (phones.length >= 2) {
    const ref = phones[0].value.replace(/[^0-9]/g, '');
    items.push({
      field: '연락처',
      values: phones.map(p => ({ channel: p.channel, value: p.value, isCorrect: p.value.replace(/[^0-9]/g, '') === ref })),
      impact: '다른 전화번호는 고객 혼란을 유발합니다',
      recommendation: '모든 플랫폼에 동일한 대표 전화번호를 등록하세요',
    });
  }

  return items;
}

function buildBrandColors(branding: Record<string, unknown> | undefined): { name: string; hex: string; usage: string }[] {
  if (!branding) return [];
  const colors: { name: string; hex: string; usage: string }[] = [];
  if (branding.primaryColor) colors.push({ name: 'Primary', hex: branding.primaryColor as string, usage: '메인 브랜드 색상' });
  if (branding.accentColor) colors.push({ name: 'Accent', hex: branding.accentColor as string, usage: '강조 색상' });
  if (branding.backgroundColor) colors.push({ name: 'Background', hex: branding.backgroundColor as string, usage: '배경 색상' });
  if (branding.textColor) colors.push({ name: 'Text', hex: branding.textColor as string, usage: '본문 텍스트' });
  return colors;
}

function buildBrandFonts(branding: Record<string, unknown> | undefined): { family: string; weight: string; usage: string; sampleText: string }[] {
  if (!branding) return [];
  const fonts: { family: string; weight: string; usage: string; sampleText: string }[] = [];
  if (branding.headingFont) fonts.push({ family: branding.headingFont as string, weight: 'Bold', usage: '제목/헤딩', sampleText: '안전이 예술이 되는 곳' });
  if (branding.bodyFont) fonts.push({ family: branding.bodyFont as string, weight: 'Regular', usage: '본문 텍스트', sampleText: '프리미엄 의료 서비스를 경험하세요' });
  return fonts;
}

/**
 * Supabase report 원본 row를 MarketingPlan으로 변환.
 * report 데이터 (채널 분석, 추천사항, 서비스)를 사용해
 * 플랜 콘텐츠를 동적으로 생성.
 */
export function transformReportToPlan(row: RawReportRow): MarketingPlan {
  const report = row.report;
  const clinicInfo = report.clinicInfo as Record<string, unknown> | undefined;
  const channelAnalysis = report.channelAnalysis as Record<string, Record<string, unknown>> | undefined;
  const recommendations = report.recommendations as Record<string, unknown>[] | undefined;
  const services = (clinicInfo?.services as string[]) || [];
  const enrichment = report.channelEnrichment as EnrichmentData | undefined;
  const scrapeData = row.scrape_data as Record<string, unknown> | undefined;
  const branding = scrapeData?.branding as Record<string, unknown> | undefined;

  const channelStrategies = buildChannelStrategies(channelAnalysis, recommendations);
  const pillars = buildContentPillars(recommendations, services);
  const clinicName = (clinicInfo?.name as string) || row.clinic_name || '';
  const calendar = buildCalendar(channelStrategies, pillars, services, enrichment, clinicName, report);

  return {
    id: row.id,
    reportId: row.id,
    clinicName: (clinicInfo?.name as string) || row.clinic_name || '',
    clinicNameEn: (clinicInfo?.nameEn as string) || '',
    createdAt: row.created_at,
    targetUrl: row.url,

    brandGuide: {
      colors: buildBrandColors(branding),
      fonts: buildBrandFonts(branding),
      logoRules: [],
      toneOfVoice: {
        personality: ['전문적', '친근한', '신뢰할 수 있는'],
        communicationStyle: '의료 전문 지식을 쉽고 친근하게 전달',
        doExamples: ['정확한 의학 용어 사용', '환자 성공 사례 공유', '전문의 인사이트 제공'],
        dontExamples: ['과장된 효과 주장', '비교 광고', '의학적 보장 표현'],
      },
      channelBranding: buildChannelBrandingFromEnrichment(enrichment),
      brandInconsistencies: buildBrandInconsistencies(enrichment, (clinicInfo?.name as string) || row.clinic_name || ''),
    },

    channelStrategies,

    contentStrategy: {
      pillars,
      typeMatrix: [
        { format: '숏폼 영상 (60초)', channels: ['YouTube Shorts', 'Instagram Reels', 'TikTok'], frequency: '주 3-5회', purpose: '신규 유입 + 인지도' },
        { format: '롱폼 영상 (5-15분)', channels: ['YouTube'], frequency: '주 1회', purpose: '전문성 + 검색 SEO' },
        { format: '블로그 포스트', channels: ['네이버 블로그'], frequency: '주 2-3회', purpose: 'SEO + 상세 정보' },
        { format: '피드 이미지', channels: ['Instagram', 'Facebook'], frequency: '주 3회', purpose: '브랜드 인지도' },
      ],
      workflow: [
        { step: 1, name: '기획', description: '콘텐츠 주제 선정 + 키워드 리서치', owner: 'AI + 마케터', duration: '30분' },
        { step: 2, name: '제작', description: 'AI 초안 생성 + 의료진 감수', owner: 'INFINITH AI', duration: '1시간' },
        { step: 3, name: '편집', description: '영상/이미지 편집 + 자막 추가', owner: 'INFINITH Studio', duration: '30분' },
        { step: 4, name: '배포', description: '채널별 최적화 + 스케줄 배포', owner: 'INFINITH Distribution', duration: '자동' },
        { step: 5, name: '분석', description: '성과 데이터 수집 + 최적화 제안', owner: 'INFINITH Analytics', duration: '자동' },
      ],
      repurposingSource: '1개 롱폼 영상',
      repurposingOutputs: [
        { format: '숏폼 영상 3개', channel: 'YouTube Shorts / Instagram Reels', description: '핵심 장면 추출' },
        { format: '블로그 포스트', channel: '네이버 블로그', description: '영상 스크립트 기반 SEO 글' },
        { format: '피드 이미지 4장', channel: 'Instagram / Facebook', description: '핵심 정보 카드뉴스' },
        { format: '카카오톡 메시지', channel: 'KakaoTalk', description: '환자 타겟 CTA 메시지' },
      ],
    },

    calendar,

    assetCollection: buildAssets(enrichment),
  };
}
