import { Ripgrep } from "../file/ripgrep"

import { Instance } from "../project/instance"

import PROMPT_ANTHROPIC from "./prompt/anthropic.txt"
import PROMPT_ANTHROPIC_WITHOUT_TODO from "./prompt/qwen.txt"
import PROMPT_BEAST from "./prompt/beast.txt"
import PROMPT_GEMINI from "./prompt/gemini.txt"

import PROMPT_CODEX from "./prompt/codex_header.txt"
import PROMPT_TRINITY from "./prompt/trinity.txt"
import PROMPT_WORDPRESS from "./prompt/wordpress-plugin.txt"
import type { Provider } from "@/provider/provider"
import * as fs from "fs/promises"
import * as path from "path"

export namespace SystemPrompt {
  export function instructions() {
    return PROMPT_CODEX.trim()
  }

  let wordpressDetectionCache: boolean | null = null
  let wordpressDetectionCacheTime = 0
  const WORDPRESS_CACHE_TTL_MS = 30000

  export async function detectWordPressProject(): Promise<boolean> {
    const now = Date.now()
    if (wordpressDetectionCache !== null && (now - wordpressDetectionCacheTime) < WORDPRESS_CACHE_TTL_MS) {
      return wordpressDetectionCache
    }

    const cwd = Instance.directory
    if (!cwd) {
      return false
    }
    
    // All plugins from the builder are WordPress plugins
    // Builder workspaces are typically under /apps/ or similar patterns
    const project = Instance.project
    const isBuilderWorkspace = !project.vcs && (
      cwd.includes('/apps/') ||
      cwd.includes('\\apps\\') ||
      cwd.includes('/home/web/data/apps/')
    )
    
    if (isBuilderWorkspace) {
      wordpressDetectionCache = true
      wordpressDetectionCacheTime = now
      return true
    }
    
    const isWordPress = await detectWordPressInDirectory(cwd)
    
    wordpressDetectionCache = isWordPress
    wordpressDetectionCacheTime = now
    return isWordPress
  }

  async function detectWordPressInDirectory(dir: string): Promise<boolean> {
    try {
      const entries = await fs.readdir(dir, { withFileTypes: true })
      
      for (const entry of entries) {
        if (entry.isFile() && entry.name.endsWith('.php')) {
          const content = await fs.readFile(path.join(dir, entry.name), 'utf8')
          if (isWordPressPluginFile(content)) {
            return true
          }
        }
        
        if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
          const subDirFiles = await fs.readdir(path.join(dir, entry.name))
          for (const file of subDirFiles) {
            if (file.endsWith('.php')) {
              const content = await fs.readFile(path.join(dir, entry.name, file), 'utf8')
              if (isWordPressPluginFile(content)) {
                return true
              }
            }
          }
        }
      }
    } catch (error) {
      return false
    }
    
    return false
  }

  function isWordPressPluginFile(content: string): boolean {
    const hasPluginName = /Plugin Name:/i.test(content)
    const hasPluginUri = /Plugin URI:/i.test(content)
    const hasWordPressFunctions = /(add_action|add_filter|register_activation_hook|wp_enqueue_script|wp_enqueue_style)/.test(content)
    
    return hasPluginName || (hasPluginUri && hasWordPressFunctions)
  }

  export async function provider(model: Provider.Model, isWordPress: boolean = false) {
    const basePrompts: string[] = []
    
    if (model.api.id.includes("gpt-5")) basePrompts.push(PROMPT_CODEX)
    else if (model.api.id.includes("gpt-") || model.api.id.includes("o1") || model.api.id.includes("o3"))
      basePrompts.push(PROMPT_BEAST)
    else if (model.api.id.includes("gemini-")) basePrompts.push(PROMPT_GEMINI)
    else if (model.api.id.includes("claude")) basePrompts.push(PROMPT_ANTHROPIC)
    else if (model.api.id.toLowerCase().includes("trinity")) basePrompts.push(PROMPT_TRINITY)
    else basePrompts.push(PROMPT_ANTHROPIC_WITHOUT_TODO)

    if (isWordPress) {
      basePrompts.push(PROMPT_WORDPRESS)
    }

    return basePrompts
  }

  export async function environment(model: Provider.Model) {
    const project = Instance.project
    return [
      [
        `You are powered by the model named ${model.api.id}. The exact model ID is ${model.providerID}/${model.api.id}`,
        `Here is some useful information about the environment you are running in:`,
        `<env>`,
        `  Working directory: ${Instance.directory}`,
        `  Is directory a git repo: ${project.vcs === "git" ? "yes" : "no"}`,
        `  Platform: ${process.platform}`,
        `  Today's date: ${new Date().toDateString()}`,
        `</env>`,
        `<directories>`,
        `  ${
          project.vcs === "git" && false
            ? await Ripgrep.tree({
                cwd: Instance.directory,
                limit: 50,
              })
            : ""
        }`,
        `</directories>`,
      ].join("\n"),
    ]
  }
}
