#!/usr/bin/env node

/**
 * Cody CLI postinstall cleanup
 *
 * Removes stale cached data from older builds that may cause:
 * - Wrong OAuth URLs (pointing to upstream instead of ainative.studio)
 * - Stale theme/settings that reference old branding
 * - Cached tokens with wrong scopes
 */

const fs = require('fs')
const path = require('path')
const os = require('os')

const HOME = os.homedir()
const STALE_MARKERS = ['anthropic.com/api', 'claude.ai/api', 'console.anthropic.com']

function cleanDir(dirPath, description) {
  if (!fs.existsSync(dirPath)) return

  try {
    // Check for stale OAuth tokens with wrong URLs
    const credFiles = ['credentials.json', 'oauth.json', 'tokens.json', '.credentials']
    for (const f of credFiles) {
      const fp = path.join(dirPath, f)
      if (fs.existsSync(fp)) {
        try {
          const content = fs.readFileSync(fp, 'utf8')
          if (STALE_MARKERS.some(m => content.includes(m))) {
            fs.unlinkSync(fp)
            console.log(`  Cleaned stale credentials: ${f}`)
          }
        } catch {}
      }
    }

    // Clean stale settings that reference old branding
    const settingsFile = path.join(dirPath, 'settings.json')
    if (fs.existsSync(settingsFile)) {
      try {
        const content = fs.readFileSync(settingsFile, 'utf8')
        if (STALE_MARKERS.some(m => content.includes(m))) {
          fs.unlinkSync(settingsFile)
          console.log(`  Cleaned stale settings`)
        }
      } catch {}
    }

    // Clean old cached responses
    const cacheDir = path.join(dirPath, 'cache')
    if (fs.existsSync(cacheDir)) {
      try {
        fs.rmSync(cacheDir, { recursive: true, force: true })
        console.log(`  Cleared cache`)
      } catch {}
    }
  } catch {}
}

// Only run cleanup, never fail the install
try {
  const configDirs = [
    path.join(HOME, '.cody'),
    path.join(HOME, '.config', 'cody-cli'),
  ]

  let cleaned = false
  for (const dir of configDirs) {
    if (fs.existsSync(dir)) {
      cleanDir(dir, dir)
      cleaned = true
    }
  }

  if (cleaned) {
    console.log('Cody CLI: cleaned stale data from previous versions.')
  }
} catch {
  // Never fail install due to cleanup
}
