#!/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 successPost = data.posts.find((p: any) => p.title === '正確的 hashtag 帶你上天堂')
  const failPost = data.posts.find((p: any) => p.title.includes('一點都不難'))

  console.log('=== SUCCESSFUL POST ===')
  console.log('Title:', successPost.title)
  console.log('HTML content length:', successPost.content?.length)

  const successLexical = htmlToLexical(successPost.content || '')
  console.log('Lexical JSON length:', successLexical.length)
  const successParsed = JSON.parse(successLexical)
  console.log('Lexical children count:', successParsed.root?.children?.length)

  console.log('\n=== FAILED POST ===')
  console.log('Title:', failPost.title)
  console.log('HTML content length:', failPost.content?.length)

  const failLexical = htmlToLexical(failPost.content || '')
  console.log('Lexical JSON length:', failLexical.length)
  const failParsed = JSON.parse(failLexical)
  console.log('Lexical children count:', failParsed.root?.children?.length)

  // Check for special characters in HTML
  console.log('\n=== CHARACTER CHECK ===')
  const specialChars = /["\n\r\t]/
  const failMatches = (failPost.content?.match(specialChars) || []).length
  const successMatches = (successPost.content?.match(specialChars) || []).length
  console.log('Special chars in fail post:', failMatches)
  console.log('Special chars in success post:', successMatches)

  // Look for empty text nodes
  let emptyTextCount = 0
  failParsed.root?.children?.forEach((child: any) => {
    child.children?.forEach((grandchild: any) => {
      if (grandchild.type === 'text' && grandchild.text === '') {
        emptyTextCount++
      }
    })
  })
  console.log('Empty text nodes in fail post:', emptyTextCount)
}

main().catch(console.error)
