import * as fs from 'fs';
import * as path from 'path';
import * as cp from 'child_process';
import * as util from 'util';
import { Minimatch } from 'minimatch';

const execAsync = util.promisify(cp.exec);

// ---------------------------------------------------------------------------
// Context passed to every tool call — workspace root + credentials
// ---------------------------------------------------------------------------

export interface ToolContext {
    workspaceRoot: string;
    gitea: {
        apiUrl: string;
        apiToken: string;
        username: string;
    };
    coolify: {
        apiUrl: string;
        apiToken: string;
    };
}

// ---------------------------------------------------------------------------
// Tool definitions (schema for Gemini function calling)
// ---------------------------------------------------------------------------

export interface ToolDefinition {
    name: string;
    description: string;
    parameters: Record<string, unknown>;
}

export const ALL_TOOLS: ToolDefinition[] = [
    {
        name: 'read_file',
        description: 'Read the complete content of a file in the workspace. Always read before editing.',
        parameters: {
            type: 'object',
            properties: {
                path: { type: 'string', description: 'Relative path from workspace root (e.g. "src/index.ts")' }
            },
            required: ['path']
        }
    },
    {
        name: 'write_file',
        description: 'Write complete content to a file. Creates parent directories if needed. Overwrites existing files.',
        parameters: {
            type: 'object',
            properties: {
                path: { type: 'string', description: 'Relative path from workspace root' },
                content: { type: 'string', description: 'Complete new file content' }
            },
            required: ['path', 'content']
        }
    },
    {
        name: 'replace_in_file',
        description: 'Replace an exact string in a file. The old_content must match character-for-character. Read the file first.',
        parameters: {
            type: 'object',
            properties: {
                path: { type: 'string', description: 'Relative path from workspace root' },
                old_content: { type: 'string', description: 'Exact text to replace' },
                new_content: { type: 'string', description: 'Replacement text' }
            },
            required: ['path', 'old_content', 'new_content']
        }
    },
    {
        name: 'list_directory',
        description: 'List files and subdirectories in a directory. Directories have trailing "/".',
        parameters: {
            type: 'object',
            properties: {
                path: { type: 'string', description: 'Relative path from workspace root. Use "." for root.' }
            },
            required: ['path']
        }
    },
    {
        name: 'find_files',
        description: 'Find files matching a glob pattern in the workspace. Returns up to 200 relative paths.',
        parameters: {
            type: 'object',
            properties: {
                pattern: { type: 'string', description: 'Glob pattern e.g. "**/*.ts", "src/**/*.test.js"' }
            },
            required: ['pattern']
        }
    },
    {
        name: 'search_code',
        description: 'Search file contents for a string or regex pattern. Returns file path, line number, and matching line.',
        parameters: {
            type: 'object',
            properties: {
                query: { type: 'string', description: 'Search term or regex' },
                file_extensions: {
                    type: 'array',
                    items: { type: 'string' },
                    description: 'Optional: limit to these extensions e.g. ["ts","js"]'
                }
            },
            required: ['query']
        }
    },
    {
        name: 'execute_command',
        description: 'Run a shell command in the workspace and return stdout + stderr. 120s timeout. Use for: npm install, npm test, git status, building, etc.',
        parameters: {
            type: 'object',
            properties: {
                command: { type: 'string', description: 'Shell command to run' },
                working_directory: { type: 'string', description: 'Optional: relative subdirectory to run in' }
            },
            required: ['command']
        }
    },
    {
        name: 'git_commit_and_push',
        description: 'Stage all changes, commit with a message, and push to the remote. Call this when work is complete.',
        parameters: {
            type: 'object',
            properties: {
                message: { type: 'string', description: 'Commit message describing the changes made' }
            },
            required: ['message']
        }
    },
    {
        name: 'coolify_list_projects',
        description: 'List all projects in the Coolify instance. Returns project names and UUIDs.',
        parameters: { type: 'object', properties: {} }
    },
    {
        name: 'coolify_list_applications',
        description: 'List applications in a Coolify project.',
        parameters: {
            type: 'object',
            properties: {
                project_uuid: { type: 'string', description: 'Project UUID from coolify_list_projects' }
            },
            required: ['project_uuid']
        }
    },
    {
        name: 'coolify_deploy',
        description: 'Trigger a deployment for a Coolify application.',
        parameters: {
            type: 'object',
            properties: {
                application_uuid: { type: 'string', description: 'Application UUID to deploy' }
            },
            required: ['application_uuid']
        }
    },
    {
        name: 'coolify_get_logs',
        description: 'Get recent deployment logs for a Coolify application.',
        parameters: {
            type: 'object',
            properties: {
                application_uuid: { type: 'string', description: 'Application UUID' }
            },
            required: ['application_uuid']
        }
    },
    {
        name: 'gitea_create_issue',
        description: 'Create a new issue in a Gitea repository.',
        parameters: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Repository in "owner/name" format' },
                title: { type: 'string', description: 'Issue title' },
                body: { type: 'string', description: 'Issue body (markdown)' },
                labels: { type: 'array', items: { type: 'string' }, description: 'Optional label names' }
            },
            required: ['repo', 'title', 'body']
        }
    },
    {
        name: 'gitea_list_issues',
        description: 'List open issues in a Gitea repository.',
        parameters: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Repository in "owner/name" format' },
                state: { type: 'string', description: '"open", "closed", or "all". Default: "open"' }
            },
            required: ['repo']
        }
    },
    {
        name: 'gitea_close_issue',
        description: 'Close an issue in a Gitea repository.',
        parameters: {
            type: 'object',
            properties: {
                repo: { type: 'string', description: 'Repository in "owner/name" format' },
                issue_number: { type: 'number', description: 'Issue number to close' }
            },
            required: ['repo', 'issue_number']
        }
    },
    {
        name: 'spawn_agent',
        description: 'Dispatch a sub-agent job to run in the background. Returns a job ID. Use this to delegate specialized work to Coder, PM, or Marketing agents.',
        parameters: {
            type: 'object',
            properties: {
                agent: { type: 'string', description: '"Coder", "PM", or "Marketing"' },
                task: { type: 'string', description: 'Detailed task description for the agent' },
                repo: { type: 'string', description: 'Gitea repo in "owner/name" format the agent should work on' }
            },
            required: ['agent', 'task', 'repo']
        }
    }
];

// ---------------------------------------------------------------------------
// Tool executor — routes call.name → implementation
// ---------------------------------------------------------------------------

export async function executeTool(
    name: string,
    args: Record<string, unknown>,
    ctx: ToolContext
): Promise<unknown> {
    switch (name) {
        case 'read_file':          return readFile(String(args.path), ctx);
        case 'write_file':         return writeFile(String(args.path), String(args.content), ctx);
        case 'replace_in_file':    return replaceInFile(String(args.path), String(args.old_content), String(args.new_content), ctx);
        case 'list_directory':     return listDirectory(String(args.path), ctx);
        case 'find_files':         return findFiles(String(args.pattern), ctx);
        case 'search_code':        return searchCode(String(args.query), args.file_extensions as string[] | undefined, ctx);
        case 'execute_command':    return executeCommand(String(args.command), args.working_directory as string | undefined, ctx);
        case 'git_commit_and_push': return gitCommitAndPush(String(args.message), ctx);
        case 'coolify_list_projects':    return coolifyListProjects(ctx);
        case 'coolify_list_applications': return coolifyListApplications(String(args.project_uuid), ctx);
        case 'coolify_deploy':     return coolifyDeploy(String(args.application_uuid), ctx);
        case 'coolify_get_logs':   return coolifyGetLogs(String(args.application_uuid), ctx);
        case 'gitea_create_issue': return giteaCreateIssue(String(args.repo), String(args.title), String(args.body), args.labels as string[] | undefined, ctx);
        case 'gitea_list_issues':  return giteaListIssues(String(args.repo), (args.state as string) || 'open', ctx);
        case 'gitea_close_issue':  return giteaCloseIssue(String(args.repo), Number(args.issue_number), ctx);
        case 'spawn_agent':        return spawnAgentTool(String(args.agent), String(args.task), String(args.repo), ctx);
        default:
            return { error: `Unknown tool: ${name}` };
    }
}

// ---------------------------------------------------------------------------
// Implementations
// ---------------------------------------------------------------------------

const EXCLUDED = new Set(['node_modules', '.git', 'dist', 'build', 'lib', '.cache', 'coverage']);

function safeResolve(root: string, rel: string): string {
    const resolved = path.resolve(root, rel);
    if (!resolved.startsWith(path.resolve(root))) {
        throw new Error(`Path escapes workspace: ${rel}`);
    }
    return resolved;
}

async function readFile(filePath: string, ctx: ToolContext): Promise<string> {
    const abs = safeResolve(ctx.workspaceRoot, filePath);
    try {
        return fs.readFileSync(abs, 'utf8');
    } catch {
        return JSON.stringify({ error: `File not found: ${filePath}` });
    }
}

async function writeFile(filePath: string, content: string, ctx: ToolContext): Promise<unknown> {
    const abs = safeResolve(ctx.workspaceRoot, filePath);
    fs.mkdirSync(path.dirname(abs), { recursive: true });
    fs.writeFileSync(abs, content, 'utf8');
    return { success: true, path: filePath, bytes: Buffer.byteLength(content) };
}

async function replaceInFile(filePath: string, oldContent: string, newContent: string, ctx: ToolContext): Promise<unknown> {
    const abs = safeResolve(ctx.workspaceRoot, filePath);
    const current = fs.readFileSync(abs, 'utf8');
    if (!current.includes(oldContent)) {
        return { error: 'old_content not found in file. Read the file again to get the current content.' };
    }
    fs.writeFileSync(abs, current.replace(oldContent, newContent), 'utf8');
    return { success: true, path: filePath };
}

async function listDirectory(dirPath: string, ctx: ToolContext): Promise<unknown> {
    const abs = safeResolve(ctx.workspaceRoot, dirPath);
    try {
        const entries = fs.readdirSync(abs, { withFileTypes: true });
        return entries
            .filter(e => !EXCLUDED.has(e.name))
            .map(e => e.isDirectory() ? `${e.name}/` : e.name);
    } catch {
        return { error: `Directory not found: ${dirPath}` };
    }
}

async function findFiles(pattern: string, ctx: ToolContext): Promise<unknown> {
    const matcher = new Minimatch(pattern, { dot: false });
    const results: string[] = [];

    function walk(dir: string): void {
        if (results.length >= 200) return;
        let entries: fs.Dirent[];
        try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
        for (const e of entries) {
            if (EXCLUDED.has(e.name)) continue;
            const abs = path.join(dir, e.name);
            const rel = path.relative(ctx.workspaceRoot, abs).split(path.sep).join('/');
            if (e.isDirectory()) {
                walk(abs);
            } else if (matcher.match(rel)) {
                results.push(rel);
            }
        }
    }

    walk(ctx.workspaceRoot);
    return { files: results, truncated: results.length >= 200 };
}

async function searchCode(query: string, extensions: string[] | undefined, ctx: ToolContext): Promise<unknown> {
    const globPatterns = extensions?.map(e => `*.${e}`) || [];
    const args = ['--line-number', '--no-heading', '--color=never', '--max-count=30'];
    for (const ex of EXCLUDED) { args.push('--glob', `!${ex}`); }
    if (globPatterns.length > 0) { for (const g of globPatterns) args.push('--glob', g); }
    args.push('--fixed-strings', query, ctx.workspaceRoot);

    try {
        const { stdout } = await execAsync(`rg ${args.map(a => `'${a}'`).join(' ')}`, { cwd: ctx.workspaceRoot, timeout: 15000 });
        const lines = stdout.trim().split('\n').filter(Boolean).map(line => {
            const m = line.match(/^(.+?):(\d+):(.*)$/);
            if (!m) return null;
            return { file: path.relative(ctx.workspaceRoot, m[1]).split(path.sep).join('/'), line: parseInt(m[2]), content: m[3].trim() };
        }).filter(Boolean);
        return lines;
    } catch (err: any) {
        if (err.code === 1) return []; // ripgrep exit 1 = no matches
        return { error: `Search failed: ${err.message}` };
    }
}

async function executeCommand(command: string, workingDir: string | undefined, ctx: ToolContext): Promise<unknown> {
    const BLOCKED = ['rm -rf /', 'mkfs', ':(){:|:&};:'];
    if (BLOCKED.some(b => command.includes(b))) {
        return { error: 'Command blocked for safety.' };
    }
    const cwd = workingDir ? safeResolve(ctx.workspaceRoot, workingDir) : ctx.workspaceRoot;
    try {
        const { stdout, stderr } = await execAsync(command, { cwd, timeout: 120_000, maxBuffer: 1024 * 1024 });
        return { exitCode: 0, stdout: stdout.trim(), stderr: stderr.trim() };
    } catch (err: any) {
        return { exitCode: err.code, stdout: (err.stdout || '').trim(), stderr: (err.stderr || '').trim(), error: err.message };
    }
}

async function gitCommitAndPush(message: string, ctx: ToolContext): Promise<unknown> {
    const cwd = ctx.workspaceRoot;
    const { apiUrl, apiToken, username } = ctx.gitea;

    try {
        await execAsync('git add -A', { cwd });
        await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, { cwd });

        // Ensure remote has credentials
        const remoteUrl = (await execAsync('git remote get-url origin', { cwd })).stdout.trim();
        const authedUrl = remoteUrl.startsWith('https://')
            ? remoteUrl.replace('https://', `https://${username}:${apiToken}@`)
            : remoteUrl;
        await execAsync(`git push "${authedUrl}" HEAD`, { cwd, timeout: 60_000 });

        return { success: true, message };
    } catch (err: any) {
        const cleaned = (err.message || '').replace(new RegExp(apiToken, 'g'), '***');
        return { error: `Git operation failed: ${cleaned}` };
    }
}

// ---------------------------------------------------------------------------
// Coolify tools
// ---------------------------------------------------------------------------

async function coolifyFetch(path: string, ctx: ToolContext, method = 'GET', body?: unknown): Promise<unknown> {
    const res = await fetch(`${ctx.coolify.apiUrl}/api/v1${path}`, {
        method,
        headers: {
            'Authorization': `Bearer ${ctx.coolify.apiToken}`,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: body ? JSON.stringify(body) : undefined
    });
    if (!res.ok) return { error: `Coolify API error: ${res.status} ${res.statusText}` };
    return res.json();
}

async function coolifyListProjects(ctx: ToolContext): Promise<unknown> {
    return coolifyFetch('/projects', ctx);
}

async function coolifyListApplications(projectUuid: string, ctx: ToolContext): Promise<unknown> {
    const all = await coolifyFetch('/applications', ctx) as any[];
    if (!Array.isArray(all)) return all;
    return all.filter((a: any) => a.project_uuid === projectUuid);
}

async function coolifyDeploy(appUuid: string, ctx: ToolContext): Promise<unknown> {
    return coolifyFetch(`/applications/${appUuid}/deploy`, ctx, 'POST');
}

async function coolifyGetLogs(appUuid: string, ctx: ToolContext): Promise<unknown> {
    return coolifyFetch(`/applications/${appUuid}/logs?limit=50`, ctx);
}

// ---------------------------------------------------------------------------
// Gitea tools
// ---------------------------------------------------------------------------

async function giteaFetch(path: string, ctx: ToolContext, method = 'GET', body?: unknown): Promise<unknown> {
    const res = await fetch(`${ctx.gitea.apiUrl}/api/v1${path}`, {
        method,
        headers: {
            'Authorization': `token ${ctx.gitea.apiToken}`,
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: body ? JSON.stringify(body) : undefined
    });
    if (!res.ok) return { error: `Gitea API error: ${res.status} ${res.statusText}` };
    return res.json();
}

async function giteaCreateIssue(repo: string, title: string, body: string, labels: string[] | undefined, ctx: ToolContext): Promise<unknown> {
    return giteaFetch(`/repos/${repo}/issues`, ctx, 'POST', { title, body, labels });
}

async function giteaListIssues(repo: string, state: string, ctx: ToolContext): Promise<unknown> {
    return giteaFetch(`/repos/${repo}/issues?state=${state}&limit=20`, ctx);
}

async function giteaCloseIssue(repo: string, issueNumber: number, ctx: ToolContext): Promise<unknown> {
    return giteaFetch(`/repos/${repo}/issues/${issueNumber}`, ctx, 'PATCH', { state: 'closed' });
}

// ---------------------------------------------------------------------------
// Spawn agent (used by Orchestrator to delegate to specialists)
// Calls back to the AgentRunner HTTP API to queue a new job.
// ---------------------------------------------------------------------------

async function spawnAgentTool(agent: string, task: string, repo: string, _ctx: ToolContext): Promise<unknown> {
    const runnerUrl = process.env.AGENT_RUNNER_URL || 'http://localhost:3333';
    try {
        const res = await fetch(`${runnerUrl}/api/agent/run`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-Internal': 'true' },
            body: JSON.stringify({ agent, task, repo })
        });
        const data = await res.json() as any;
        return { jobId: data.jobId, agent, status: 'dispatched' };
    } catch (err) {
        return { error: `Failed to spawn agent: ${err instanceof Error ? err.message : String(err)}` };
    }
}
