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(' · ')
}

function serializePersonaDraftObject(draft: Record<string, unknown>): string {
  const line = (key: string, label: string) => {
    const value = typeof draft[key] === 'string' ? draft[key].trim() : ''
    return value ? `${label}\n${value}` : ''
  }
  return [
    line('identity', '【我是誰】'),
    line('tone', '【語氣】'),
    line('audience', '【對誰說】'),
    line('hooks', '【開場習慣】'),
    line('examples', '【代表句範例】'),
    line('avoid', '【避免】'),
  ]
    .filter(Boolean)
    .join('\n\n')
}

function normalizeStyle8DAnalysis(value: Record<string, unknown>): StoredStyle8DProfile['analysis'] | null {
  const nested = value.analysis
  if (nested && typeof nested === 'object') {
    return nested as StoredStyle8DProfile['analysis']
  }
  const flat = {} as StoredStyle8DProfile['analysis']
  let hasDimension = false
  for (const key of STYLE_8D_KEYS) {
    const dim = value[key]
    if (!dim || typeof dim !== 'object') continue
    const summary = typeof (dim as { summary?: string }).summary === 'string'
      ? (dim as { summary: string }).summary.trim()
      : ''
    const evidence = Array.isArray((dim as { evidence?: unknown }).evidence)
      ? ((dim as { evidence: string[] }).evidence ?? [])
      : []
    flat[key] = { summary, evidence }
    if (summary) hasDimension = true
  }
  return hasDimension ? flat : null
}

function normalizePersonaDraft(value: Record<string, unknown>): string {
  const draft = value.personaDraft
  if (typeof draft === 'string') return draft.trim()
  if (draft && typeof draft === 'object') return serializePersonaDraftObject(draft as Record<string, unknown>)
  return ''
}

export function parseStyle8DProfile(raw?: string | null): StoredStyle8DProfile | null {
  if (!raw?.trim()) return null
  try {
    const value = JSON.parse(raw) as Record<string, unknown>
    if (!value || typeof value !== 'object') return null
    const analysis = normalizeStyle8DAnalysis(value)
    const personaDraft = normalizePersonaDraft(value)
    if (!analysis && !personaDraft) return null
    const engagement = (value.engagement as StoredStyle8DProfile['engagement']) ?? {
      measuredPosts: 0,
      medianInteractions: 0,
      averageInteractions: 0,
      postsAboveThreshold: 0,
      threshold: 10,
      verdict: 'unknown' as const,
    }
    return {
      username: typeof value.username === 'string' ? value.username : '',
      analyzedAt: typeof value.analyzedAt === 'string' ? value.analyzedAt : '',
      postCount: typeof value.postCount === 'number' ? value.postCount : 0,
      engagement,
      samplePosts: Array.isArray(value.samplePosts) ? (value.samplePosts as Style8DSamplePost[]) : [],
      analysis: analysis ?? createEmptyStyle8DProfile().analysis,
      personaDraft,
    }
  } catch {
    return null
  }
}

export function hasPersona8D(
  persona?: { persona?: string; style_profile?: string; style_benchmark?: string } | null,
): boolean {
  if (!persona) return false
  const profile = parseStyle8DProfile(persona.style_profile)
  if (profile) {
    if (profile.personaDraft?.trim()) return true
    const hasDimension = STYLE_8D_KEYS.some((key) => profile.analysis[key]?.summary?.trim())
    if (hasDimension) return true
  }
  if (persona.style_benchmark?.trim() && (persona.persona?.trim() || persona.style_profile?.trim())) {
    return true
  }
  return !!(persona.persona?.trim() && persona.style_profile?.trim())
}

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: '樣本較少時，請以手動校對證據為準。',
      }
  }
}