#!/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 post = data.posts.find((p: any) => p.title.includes('掌握故事行銷'))

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

  console.log('All link URLs:')
  const findLinks = (nodes: any[], depth = 0) => {
    if (depth > 10) return
    nodes.forEach((node: any, i: number) => {
      if (node.type === 'link') {
        const url = node.url
        const isValid = url && url !== '#' && (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('/'))
        console.log(` [${depth}.${i}] ${url} - Valid: ${isValid}`)
      }
      if (node.children) {
        findLinks(node.children, depth + 1)
      }
    })
  }
  findLinks(parsed.root?.children || [])

  // Check raw HTML for links
  console.log('\nRaw HTML links:')
  const linkRegex = /<a[^>]+href=["']([^"']+)["'][^>]*>/gi
  let match
  const html = post.content || ''
  while ((match = linkRegex.exec(html)) !== null) {
    console.log(' ', match[1])
  }
}

main().catch(console.error)
