import type { ToolConfig } from './index'
import { apiFetch } from '@/lib/tauri'

// Uses relative URLs - works with Vite proxy in dev and Traefik in production
const API_BASE = ''

// Store credentials in memory
let giteaCredentials: {
  giteaUrl: string
  username: string
  password: string
  owner: string
  repo: string
  branch: string
} | null = null

export function setGiteaCredentials(creds: typeof giteaCredentials) {
  giteaCredentials = creds
}

export function clearGiteaCredentials() {
  giteaCredentials = null
}

export function createSourceCodeHandlers(): ToolConfig[] {
  return [
    {
      name: 'get_repo_info',
      description: 'Obtiene info del repositorio Gitea',
      category: 'source',
      schema: { type: 'object', properties: {} },
      handler: async () => {
        if (!giteaCredentials) {
          return 'No hay conexion a Gitea. Conectate primero en Source Code.'
        }

        try {
          const res = await apiFetch(`${API_BASE}/api/gitea/repo`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(giteaCredentials)
          })

          if (!res.ok) {
            const err = await res.json()
            return `Error: ${err.error}`
          }

          const data = await res.json()
          const repo = data.repo

          return `Repositorio: ${repo.owner.login}/${repo.name}\n` +
            `Descripcion: ${repo.description || 'Sin descripcion'}\n` +
            `Rama default: ${repo.default_branch}\n` +
            `Stars: ${repo.stars_count}\n` +
            `Forks: ${repo.forks_count}\n` +
            `Ramas: ${data.branches.join(', ')}`
        } catch (e: any) {
          return `Error: ${e.message}`
        }
      }
    },
    {
      name: 'list_repo_files',
      description: 'Lista archivos del repositorio',
      category: 'source',
      schema: {
        type: 'object',
        properties: {
          path: { type: 'string', description: 'Ruta dentro del repositorio' }
        }
      },
      handler: async (args: { path?: string }) => {
        if (!giteaCredentials) {
          return 'No hay conexion a Gitea'
        }

        try {
          const res = await apiFetch(`${API_BASE}/api/gitea/tree`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ...giteaCredentials, path: args.path || '' })
          })

          if (!res.ok) {
            const err = await res.json()
            return `Error: ${err.error}`
          }

          const data = await res.json()
          const path = args.path || '/'

          if (data.tree.length === 0) return `No hay archivos en ${path}`

          const folders = data.tree.filter((f: any) => f.type === 'dir')
          const files = data.tree.filter((f: any) => f.type === 'file')

          let result = `Contenido de ${path}:\n\n`

          if (folders.length > 0) {
            result += `Carpetas (${folders.length}):\n`
            result += folders.map((f: any) => `  [DIR] ${f.name}/`).join('\n')
            result += '\n\n'
          }

          if (files.length > 0) {
            result += `Archivos (${files.length}):\n`
            result += files.map((f: any) => `  ${f.name}`).join('\n')
          }

          return result
        } catch (e: any) {
          return `Error: ${e.message}`
        }
      }
    },
    {
      name: 'read_repo_file',
      description: 'Lee contenido de un archivo',
      category: 'source',
      schema: {
        type: 'object',
        properties: {
          path: { type: 'string', description: 'Ruta del archivo' },
          lines: { type: 'number', description: 'Lineas maximas (default: 100)' }
        },
        required: ['path']
      },
      handler: async (args: { path: string; lines?: number }) => {
        if (!giteaCredentials) {
          return 'No hay conexion a Gitea'
        }

        try {
          const res = await apiFetch(`${API_BASE}/api/gitea/file`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ...giteaCredentials, path: args.path })
          })

          if (!res.ok) {
            const err = await res.json()
            return `Error: ${err.error}`
          }

          const data = await res.json()
          let content = data.content

          const maxLines = args.lines || 100
          const lines = content.split('\n')
          if (lines.length > maxLines) {
            content = lines.slice(0, maxLines).join('\n')
            content += `\n\n... (${lines.length - maxLines} lineas mas)`
          }

          return `Archivo: ${args.path}\nTamano: ${data.size} bytes\n\n${content}`
        } catch (e: any) {
          return `Error: ${e.message}`
        }
      }
    },
    {
      name: 'search_repo_code',
      description: 'Busca codigo en el repositorio',
      category: 'source',
      schema: {
        type: 'object',
        properties: {
          query: { type: 'string', description: 'Texto a buscar' },
          path: { type: 'string', description: 'Ruta donde buscar' },
          extension: { type: 'string', description: 'Extension de archivos' }
        },
        required: ['query']
      },
      handler: async (args: { query: string; path?: string; extension?: string }) => {
        if (!giteaCredentials) {
          return 'No hay conexion a Gitea'
        }

        try {
          const treeRes = await apiFetch(`${API_BASE}/api/gitea/tree`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ ...giteaCredentials, path: args.path || '' })
          })

          if (!treeRes.ok) return 'Error al obtener lista de archivos'

          const treeData = await treeRes.json()
          const files = treeData.tree.filter((f: any) => {
            if (f.type !== 'file') return false
            if (args.extension) {
              return f.name.endsWith(`.${args.extension}`)
            }
            return true
          })

          const results: string[] = []
          const maxFiles = 10

          for (const file of files.slice(0, maxFiles)) {
            try {
              const fileRes = await apiFetch(`${API_BASE}/api/gitea/file`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ ...giteaCredentials, path: file.path })
              })

              if (fileRes.ok) {
                const fileData = await fileRes.json()
                const lines = fileData.content.split('\n')
                const matches: string[] = []

                lines.forEach((line: string, idx: number) => {
                  if (line.toLowerCase().includes(args.query.toLowerCase())) {
                    matches.push(`  L${idx + 1}: ${line.trim().substring(0, 80)}`)
                  }
                })

                if (matches.length > 0) {
                  results.push(`${file.path}:\n${matches.slice(0, 5).join('\n')}`)
                }
              }
            } catch (e) {
              // Skip file errors
            }
          }

          if (results.length === 0) {
            return `No se encontro "${args.query}"`
          }

          return `Busqueda: "${args.query}"\n\n${results.join('\n\n')}`
        } catch (e: any) {
          return `Error: ${e.message}`
        }
      }
    }
  ]
}
