#!/usr/bin/env tsx
/**
 * Analyze Post Data Structure
 * Compares migrated posts vs manually created posts
 */

import { config as dotenvConfig } from 'dotenv'
dotenvConfig({ path: '.env' })

import { getPayload } from 'payload'
import config from '../../src/payload.config'

async function main() {
  const payload = await getPayload({ config })

  console.log('🔍 Fetching posts for analysis...\n')

  const posts = await payload.find({
    collection: 'posts',
    limit: 5,
    depth: 0,
  })

  if (posts.docs.length === 0) {
    console.log('No posts found')
    return
  }

  // Analyze first post in detail
  const post = posts.docs[0]

  console.log('═══════════════════════════════════════════════════════════')
  console.log(`POST: "${post.title}"`)
  console.log('═══════════════════════════════════════════════════════════\n')

  // Basic info
  console.log('📋 BASIC INFO:')
  console.log(`  ID: ${post.id}`)
  console.log(`  Slug: ${post.slug}`)
  console.log(`  Status: ${post.status}`)
  console.log(`  Created: ${post.createdAt}`)

  // Content analysis
  console.log('\n📝 CONTENT FIELD:')
  console.log(`  Type: ${typeof post.content}`)
  console.log(`  Is String: ${typeof post.content === 'string'}`)
  console.log(`  Is Object: ${typeof post.content === 'object'}`)

  if (typeof post.content === 'string') {
    console.log(`  String Length: ${post.content.length} chars`)

    try {
      const parsed = JSON.parse(post.content)
      console.log(`  Parsed Type: ${parsed?.type}`)
      console.log(`  Parsed Version: ${parsed?.version}`)
      console.log(`  Children Count: ${parsed?.children?.length}`)

      // Show first child structure
      if (parsed?.children?.[0]) {
        console.log('\n  First Child:')
        const firstChild = parsed.children[0]
        console.log(`    Type: ${firstChild.type}`)
        console.log(`    Version: ${firstChild.version}`)
        if (firstChild.children) {
          console.log(`    Has Children: true (${firstChild.children.length})`)
          if (firstChild.children[0]) {
            console.log(`    First Grandchild: ${JSON.stringify(firstChild.children[0], null, 2).split('\n').join('\n      ')}`)
          }
        }
      }

      // Show full structure
      console.log('\n  FULL LEXICAL STRUCTURE:')
      console.log('  ' + JSON.stringify(parsed, null, 2).split('\n').join('\n  '))
    } catch (e) {
      console.log(`  Parse Error: ${e}`)
      console.log(`  Raw Content (first 500 chars): ${post.content.substring(0, 500)}...`)
    }
  } else if (typeof post.content === 'object') {
    console.log('  OBJECT STRUCTURE:')
    console.log('  ' + JSON.stringify(post.content, null, 2).split('\n').join('\n  '))
  }

  // Other fields
  console.log('\n🏷️  OTHER FIELDS:')
  console.log(`  Excerpt: ${post.excerpt?.substring(0, 100) || 'none'}...`)
  console.log(`  PublishedAt: ${post.publishedAt}`)
  console.log(`  Categories: ${post.categories?.length || 0} items`)

  if (post.heroImage) {
    console.log(`  HeroImage: ${typeof post.heroImage} = ${post.heroImage}`)
  }

  console.log('\n═══════════════════════════════════════════════════════════')
}

main().catch(console.error)
