export const STYLE_8D_KEYS = [
  'd1Tone',
  'd2Structure',
  'd3Interaction',
  'd4Topics',
  'd5Rhythm',
  'd6Visual',
  'd7Conversion',
  'd8Risk',
] as const

export type Style8DKey = (typeof STYLE_8D_KEYS)[number]

export const STYLE_8D_LABELS: Record<Style8DKey, string> = {
  d1Tone: 'D1 語氣人格',
  d2Structure: 'D2 結構模板',
  d3Interaction: 'D3 互動方式',
  d4Topics: 'D4 主題分布',
  d5Rhythm: 'D5 發文節奏',
  d6Visual: 'D6 視覺語法',
  d7Conversion: 'D7 轉換方式',
  d8Risk: 'D8 風險紅線',
}

export interface Style8DSamplePost {
  text: string
  permalink?: string
  like_count?: number
  reply_count?: number
}

export interface StoredStyle8DProfile {
  username: string
  analyzedAt: string
  postCount: number
  engagement: {
    measuredPosts: number
    medianInteractions: number
    averageInteractions: number
    postsAboveThreshold: number
    threshold: number
    verdict: 'strong' | 'usable' | 'unknown'
  }
  samplePosts?: Style8DSamplePost[]
  analysis: Record<Style8DKey, { summary: string; evidence: string[] }>
  personaDraft: string
}

export function createEmptyStyle8DProfile(username = ''): StoredStyle8DProfile {
  const emptyDimension = () => ({ summary: '', evidence: [] as string[] })
  return {
    username,
    analyzedAt: '',
    postCount: 0,
    engagement: {
      measuredPosts: 0,
      medianInteractions: 0,
      averageInteractions: 0,
      postsAboveThreshold: 0,
      threshold: 10,
      verdict: 'unknown',
    },
    analysis: {
      d1Tone: emptyDimension(),
      d2Structure: emptyDimension(),
      d3Interaction: emptyDimension(),
      d4Topics: emptyDimension(),
      d5Rhythm: emptyDimension(),
      d6Visual: emptyDimension(),
      d7Conversion: emptyDimension(),
      d8Risk: emptyDimension(),
    },
    samplePosts: [],
    personaDraft: '',
  }
}

export function formatStyle8DEngagementLine(profile: StoredStyle8DProfile): string {
  const { engagement, postCount, username } = profile
  const parts = [
    `@${username}`,
    `${postCount} 篇樣本`,
    `中位互動 ${engagement.medianInteractions}`,
  ]
  if (engagement.verdict === 'strong') {
    parts.push('互動穩定')
  }
  return parts.join(' · ')
}

export function parseStyle8DProfile(raw?: string | null): StoredStyle8DProfile | null {
  if (!raw?.trim()) return null
  try {
    const value = JSON.parse(raw) as StoredStyle8DProfile
    if (!value?.analysis) return null
    return value
  } catch {
    return null
  }
}

export function buildStyle8DPromptBlock(raw?: string | null): string | null {
  const profile = parseStyle8DProfile(raw)
  if (!profile) return null
  const dimensions = STYLE_8D_KEYS.map((key) => {
    const summary = profile.analysis[key]?.summary?.trim()
    return summary ? `${STYLE_8D_LABELS[key]}：${summary}` : null
  }).filter(Boolean)
  if (dimensions.length === 0) return null
  return `【8D 風格策略】\n產文與回覆都必須遵守：\n${dimensions.join('\n')}`
}

export const STYLE_8D_PIPELINE_STEPS = [
  { id: 'session', title: '確認連線', hint: '確認 Threads Extension 同步狀態' },
  { id: 'samples', title: '抓取樣本', hint: '讀取對標帳號近期貼文與公開互動' },
  { id: 'style', title: 'AI 8D', hint: '分析語氣、結構、互動、主題、節奏、視覺、轉換與風險' },
  { id: 'store', title: '儲存策略', hint: '寫入人設，供產文與回覆自動使用' },
] as const

export function style8DEngagementNotice(verdict: StoredStyle8DProfile['engagement']['verdict']) {
  switch (verdict) {
    case 'strong':
      return {
        tone: 'success' as const,
        title: '近期互動穩定，適合當對標',
        message: '判斷採用近期貼文的讚 + 回覆×2；公開頁沒有可靠瀏覽數時不會捏造。',
      }
    case 'usable':
      return {
        tone: 'warning' as const,
        title: '可參考風格，但互動門檻不高',
        message: '建議以語氣與結構為主，勿過度依賴互動表現。',
      }
    default:
      return {
        tone: 'warning' as const,
        title: '公開互動資料不足',
        message: '樣本較少時，請以手動校對證據為準。',
      }
  }
}