import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

import { _electron as electron, expect, test } from '@playwright/test'

const here = dirname(fileURLToPath(import.meta.url))
const MAIN = join(here, '..', 'out', 'main', 'index.js')

// Opt-in (GITEA_LIVE=1 + COMMITEA_MODEL_LIVE=1 + a local model on :1234). Launches
// WITHOUT COMMITEA_E2E so capture_work runs the real decomposition. It Discards at
// the end so the run never files junk issues (the create-issue POST is unit-tested).
test.describe('live capture_work', () => {
  test('decomposes a braindump into a reviewable ticket set', async () => {
    test.skip(!process.env.GITEA_LIVE || !process.env.COMMITEA_MODEL_LIVE, 'live model test — opt-in')
    test.setTimeout(300_000)
    const app = await electron.launch({ args: [MAIN], env: { ...process.env } })
    const win = await app.firstWindow()
    await win.waitForLoadState('domcontentloaded')
    const rail = win.getByRole('navigation', { name: 'Primary' })

    await rail.getByRole('button', { name: 'Capture' }).click()
    await expect(win.getByRole('heading', { name: 'Capture' })).toBeVisible()
    // the braindump is prefilled; run the real decomposition
    await win.getByRole('button', { name: 'Brew tickets' }).click()

    // capture_work → the review tray with a real, estimated ticket set
    await expect(win.getByText(/tickets · ~\d+d of work/)).toBeVisible({ timeout: 240_000 })
    await expect(win.getByRole('button', { name: 'Approve all' })).toBeVisible()
    await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-capture.png'), fullPage: true, animations: 'disabled' })

    // Discard — never file junk issues into the real repo from a test
    await win.getByRole('button', { name: 'Discard' }).click()
    await expect(win.getByRole('button', { name: 'Brew tickets' })).toBeVisible()

    await app.close()
  })
})
