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 Reginald runs the real agent loop against the real repo.
test.describe('live Reginald', () => {
  test('answers a question by consulting the real project', async () => {
    test.skip(!process.env.GITEA_LIVE || !process.env.COMMITEA_MODEL_LIVE, 'live model test — opt-in')
    test.setTimeout(300_000) // a big local model is slow: ~2 calls/turn + a reconcile
    const app = await electron.launch({ args: [MAIN], env: { ...process.env } })
    const win = await app.firstWindow()
    await win.waitForLoadState('domcontentloaded')

    // model configured → the live greeting + header (the loaded model, not the scripted demo)
    await expect(win.getByText(/· local$/)).toBeVisible({ timeout: 20000 })
    await expect(win.getByText(/I check the real board before I answer/)).toBeVisible()

    const composer = win.getByPlaceholder(/Tell me what to do/)
    await composer.fill('What should I work on right now?')
    await composer.press('Enter')

    // the agent loop ran end-to-end: it consulted the project, then answered
    await expect(win.getByText(/consulted the project/)).toBeVisible({ timeout: 240_000 })
    await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-reginald.png'), fullPage: true, animations: 'disabled' })

    await app.close()
  })

  test('proposes an estimate change for inline approval (writes via chat)', 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')
    await expect(win.getByText(/· local$/)).toBeVisible({ timeout: 20000 })

    const composer = win.getByPlaceholder(/Tell me what to do/)
    await composer.fill('Set the estimate on issue #3 to est/5d.')
    await composer.press('Enter')

    // propose_change → an inline propose-approve card (never an auto-write)
    await expect(win.getByText('Proposed · #3')).toBeVisible({ timeout: 240_000 })
    await expect(win.getByText(/→ est\/5d/)).toBeVisible()
    await win.screenshot({ path: join(here, '.artifacts', 'screens', 'live-reginald-propose.png'), fullPage: true, animations: 'disabled' })
    // Dismiss so the live run never mutates the repo (the write path itself is #41-tested)
    await win.getByRole('button', { name: 'Dismiss' }).click()
    await expect(win.getByText(/Left #3 as it was/)).toBeVisible()

    await app.close()
  })
})
