#!/usr/bin/env tsx
import { config as dotenvConfig } from 'dotenv'
import { resolve, dirname } from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const envPath = resolve(__dirname, '../../.env')

dotenvConfig({ path: envPath })

import { parseWebflowCSV } from './csvParser'
import { htmlToLexical } from './lexicalConverter'

async function main() {
  const data = await parseWebflowCSV('/Users/pukpuk/Dev/website-enchun-mgr/恩群數位行銷 - 行銷放大鏡集.csv')
  const failPost = data.posts.find((p: any) => p.title.includes('一點都不難'))

  const lexical = htmlToLexical(failPost.content || '')
  const parsed = JSON.parse(lexical)

  console.log('Root type:', parsed.root?.type)
  console.log('Root version:', parsed.root?.version)
  console.log('Children count:', parsed.root?.children?.length)

  // Check each child
  let issueCount = 0
  parsed.root?.children?.forEach((child: any, i: number) => {
    if (!child.type) {
      console.log('Child', i, 'missing type')
      issueCount++
    }
    if (!child.version) {
      console.log('Child', i, 'missing version')
      issueCount++
    }
    if (!child.children || !Array.isArray(child.children)) {
      console.log('Child', i, 'missing or invalid children array')
      issueCount++
    }
  })

  console.log('Issues found:', issueCount)

  // Show first few children
  console.log('\nFirst 3 children:')
  parsed.root?.children?.slice(0, 3).forEach((child: any, i: number) => {
    console.log(`[${i}]`, JSON.stringify(child, null, 2))
  })
}

main().catch(console.error)
