// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========

import { describe, expect, it } from 'vitest'
import { OpsRegistry } from '../ops/registry.ts'
import { RAMResource } from '../resource/ram/ram.ts'
import { MountMode } from '../types.ts'
import { getTestParser, stderrStr, stdoutStr } from './fixtures/workspace_fixture.ts'
import { Workspace } from './workspace.ts'

async function makeWs(): Promise<Workspace> {
  const parser = await getTestParser()
  const r = new RAMResource()
  r.store.dirs.add('/')
  const registry = new OpsRegistry()
  registry.registerResource(r)
  return new Workspace(
    { '/ram/': r },
    { mode: MountMode.WRITE, ops: registry, shellParser: parser },
  )
}

describe('--help and man through the executor', () => {
  it('--help on a builtin renders help text without invoking the handler', async () => {
    const ws = await makeWs()
    const io = await ws.execute('cat --help')
    const out = stdoutStr(io)
    expect(io.exitCode).toBe(0)
    expect(out).toContain('Usage: cat')
    expect(out).toContain('--help')
  })

  it('man <cmd> prints help from the existing handleMan', async () => {
    const ws = await makeWs()
    const io = await ws.execute('man cat')
    const out = stdoutStr(io)
    expect(io.exitCode).toBe(0)
    expect(out).toContain('cat')
  })

  it('man with no args lists every command grouped by resource kind', async () => {
    const ws = await makeWs()
    const io = await ws.execute('man')
    const out = stdoutStr(io)
    expect(io.exitCode).toBe(0)
    expect(out).toContain('# ram')
    expect(out).toContain('- cat')
    expect(out).toContain('- ls')
    expect(out).toContain('# general')
  })

  it('man on an unknown command exits 1', async () => {
    const ws = await makeWs()
    const io = await ws.execute('man definitely-not-a-real-command')
    expect(io.exitCode).toBe(1)
    expect(stderrStr(io)).toContain('no entry for')
  })

  it('workspace filePrompt mentions --help and man (with and without args)', async () => {
    const ws = await makeWs()
    const prompt = ws.filePrompt
    expect(prompt).toContain('--help')
    expect(prompt).toContain('man <cmd>')
    expect(prompt).toContain('`man`')
  })
})
