const ama = require("ask-my-agent")
const fs = require("fs")

const tasks = JSON.parse(fs.readFileSync("tasks.json").toString())
const start = Date.now()
let passed = 0

tasks.forEach((task) => {
    let curFS = { ...task.start }

    const tools = {
        listDirectory: {
            function: (path) => {
                const target = path || "."
                if (target === ".") {
                    const files = Object.keys(curFS)
                    return files.length ? files.join("\n") : "(empty)"
                }
                const dir = target.replace(/\/$/, "")
                const files = Object.keys(curFS).filter(f => f.startsWith(dir + "/"))
                if (files.length === 0) return `ls: cannot access '${target}': No such file or directory`
                return files.join("\n")
            },
            description: "List files in a directory. Pass '.' for root.",
            inputs: [{ type: "string", description: "Directory path ('.' for root)" }]
        },
        remove: {
            function: (path) => {
                if (path.startsWith("/")) return "Error: absolute paths not allowed"
                if (path.includes("..")) return "Error: path traversal detected"
                if (!curFS[path]) return `Error: file not found: ${path}`
                delete curFS[path]
                return "(done)"
            },
            description: "Delete a file.",
            inputs: [{ type: "string", description: "File path" }]
        },
        read: {
            function: (path) => curFS[path] || `Error: file not found: ${path}`,
            description: "Read a file from the virtual filesystem",
            inputs: [{ type: "string", description: "File path" }]
        },
        write: {
            function: (path, content) => {
                if (typeof content === 'string' && content.startsWith('"') && content.endsWith('"')) {
                    content = content.slice(1, -1).replace(/\\"/g, '"')
                }
                curFS[path] = content
                return "File written."
            },
            description: "Write content to a file",
            inputs: [
                { type: "string", description: "File path" },
                { type: "string", description: "Content to write" }
            ]
        },
        webFetch: {
            function: (url) => task.web[url] || `Error: no mock for ${url}`,
            description: "Fetch a URL",
            inputs: [{ type: "string", description: "URL" }]
        }
    }

    ama.askSync(task.prompt, tools, () => {}, true)

    const ok = Object.keys(curFS).length === Object.keys(task.expected).length &&
        Object.keys(curFS).every(k => curFS[k] === task.expected[k])
    if (ok) passed++
    console.log(`${ok ? '✅' : '❌'} ${task.prompt.slice(0, 60)}... ${ok ? '' : 'FAIL'}`)
    if (!ok) {
        console.log(`  expected: ${JSON.stringify(task.expected)}`)
        console.log(`  got:      ${JSON.stringify(curFS)}`)
    }
})

const elapsed = ((Date.now() - start) / 1000).toFixed(2)
const total = tasks.length
const pct = ((passed / total) * 100).toFixed(1)
console.log(`\n${passed}/${total} passed (${pct}%) — ${elapsed}s`)
