import { expect } from '@playwright/test'
import type { Page } from '@playwright/test'

import defaultWorkflow from '@e2e/assets/default.json' with { type: 'json' }
import enMessages from '@/locales/en/main.json' with { type: 'json' }

import { OnboardingCoachmarks } from '@e2e/fixtures/components/Tour'
import { agentConsentTest as test } from '@e2e/fixtures/agentConsentFixture'

/**
 * Evidence-only run for PM-1497 QA. Drives each PM-1497 flow and captures a
 * full-page screenshot at every proof moment into temp/qa-evidence/pm-1497.
 * Traces come from the project's `trace: 'on'`. This file exists to produce the
 * QA bundle for PR #18431; the behavioral guarantees are asserted in the
 * sibling agentConsent*.spec.ts files.
 */

const EVIDENCE_DIR =
  '/Users/maanilverma/Documents/ComfyUI_frontend/temp/qa-evidence/pm-1497'

const AUTO_SHOWN_KEY = 'Comfy.AgentConsent.AutoShown.test-user-e2e.ws-personal'

const readAutoShown = (page: Page) =>
  page.evaluate((key) => localStorage.getItem(key), AUTO_SHOWN_KEY)

async function hideToasts(page: Page): Promise<void> {
  await page.addStyleTag({
    content:
      '.p-toast,[data-pc-name="toast"],.comfy-toast,.p-toast-message{display:none!important}'
  })
}

async function shoot(page: Page, name: string): Promise<void> {
  await hideToasts(page)
  await page.screenshot({ fullPage: true, path: `${EVIDENCE_DIR}/${name}.png` })
}

function seedRestoredDraft(
  page: Page,
  workflow: unknown,
  name: string
): Promise<void> {
  return page.addInitScript(
    ({ wf, label }) => {
      const fnv1a = (str: string): string => {
        let hash = 2166136261
        for (let i = 0; i < str.length; i++) {
          hash ^= str.charCodeAt(i)
          hash = Math.imul(hash, 16777619)
        }
        return (hash >>> 0).toString(16).padStart(8, '0')
      }
      const path = `workflows/${label}.json`
      const draftKey = fnv1a(path)
      const now = Date.now()
      localStorage.setItem(
        'Comfy.Workflow.DraftIndex.v2:personal',
        JSON.stringify({
          v: 2,
          updatedAt: now,
          order: [draftKey],
          entries: {
            [draftKey]: { path, name: label, isTemporary: true, updatedAt: now }
          }
        })
      )
      localStorage.setItem(
        `Comfy.Workflow.Draft.v2:personal:${draftKey}`,
        JSON.stringify({ data: JSON.stringify(wf), updatedAt: now })
      )
    },
    { wf: workflow, label: name }
  )
}

test.describe('PM-1497 QA evidence', { tag: ['@cloud', '@ui'] }, () => {
  const consentTitle = enMessages.agent.consent.title
  const gettingStartedTitle = enMessages.gettingStarted.title

  test.describe('F1 baseline: Getting Started owns the screen, no card', () => {
    test.use({
      agentConsentAccepted: false,
      initialSettings: { 'Comfy.TutorialCompleted': false },
      initialFeatureFlags: {
        onboarding_tour_enabled: true,
        subscription_required: true
      }
    })
    test('capture', async ({ comfyPage, agentConsentReads }) => {
      const page = comfyPage.page
      await expect(
        page.getByRole('dialog', { name: gettingStartedTitle })
      ).toBeVisible()
      await expect
        .poll(() => agentConsentReads.length, { timeout: 15_000 })
        .toBeGreaterThan(0)
      await expect(
        page.getByRole('dialog', { name: consentTitle })
      ).toHaveCount(0)
      await shoot(page, 'F1-getting-started-no-card')
    })
  })

  test.describe('F8 positive control: returning user, card offers', () => {
    test.use({ agentConsentAccepted: false })
    test('capture', async ({ comfyPage }) => {
      const page = comfyPage.page
      await expect(
        page.getByRole('dialog', { name: consentTitle })
      ).toBeVisible()
      await shoot(page, 'F8-returning-user-card')
    })
  })

  test.describe('F9 flag off: no Getting Started, card offers', () => {
    test.use({
      agentConsentAccepted: false,
      initialSettings: { 'Comfy.TutorialCompleted': false },
      initialFeatureFlags: {
        onboarding_tour_enabled: false,
        subscription_required: true
      }
    })
    test('capture', async ({ comfyPage }) => {
      const page = comfyPage.page
      await expect(
        page.getByRole('dialog', { name: consentTitle })
      ).toBeVisible()
      await expect(
        page.getByRole('dialog', { name: gettingStartedTitle })
      ).toHaveCount(0)
      await shoot(page, 'F9-flag-off-card-offers')
    })
  })

  test.describe('F10 subscription mode off: card offers', () => {
    test.use({
      agentConsentAccepted: false,
      initialSettings: { 'Comfy.TutorialCompleted': false },
      initialFeatureFlags: {
        onboarding_tour_enabled: true,
        subscription_required: false
      }
    })
    test('capture', async ({ comfyPage }) => {
      const page = comfyPage.page
      await expect(
        page.getByRole('dialog', { name: consentTitle })
      ).toBeVisible()
      await shoot(page, 'F10-subscription-off-card-offers')
    })
  })

  test.describe('F15 restored boot: no Getting Started, card offers', () => {
    test.use({
      agentConsentAccepted: false,
      initialSettings: { 'Comfy.TutorialCompleted': false },
      initialFeatureFlags: {
        onboarding_tour_enabled: true,
        subscription_required: true
      }
    })
    test.beforeEach(async ({ page }) => {
      await seedRestoredDraft(page, defaultWorkflow, 'Restored Work')
    })
    test('capture', async ({ comfyPage }) => {
      const page = comfyPage.page
      await expect
        .poll(() => page.evaluate(() => window.app?.graph?.nodes?.length ?? 0))
        .toBeGreaterThan(0)
      await expect(
        page.getByRole('dialog', { name: gettingStartedTitle })
      ).toHaveCount(0)
      await expect(
        page.getByRole('dialog', { name: consentTitle })
      ).toBeVisible()
      await shoot(page, 'F15-restored-boot-card-offers')
    })
  })

  test.describe('F11 App Mode tour holds then releases the card', () => {
    test.use({
      agentConsentAccepted: false,
      initialSettings: {
        'Comfy.TutorialCompleted': true,
        'Comfy.OnboardingCoachmarks.Seen': [],
        'Comfy.AppBuilder.VueNodeSwitchDismissed': true
      },
      initialFeatureFlags: {
        onboarding_tour_enabled: true,
        subscription_required: true
      }
    })
    test.beforeEach(async ({ page }) => {
      await seedRestoredDraft(
        page,
        {
          ...defaultWorkflow,
          extra: {
            ...defaultWorkflow.extra,
            linearMode: true,
            linearData: { inputs: [], outputs: ['9'] }
          }
        },
        'App'
      )
    })
    test('capture', async ({ comfyPage }) => {
      const page = comfyPage.page
      const onboarding = new OnboardingCoachmarks(page)
      const consent = page.getByRole('dialog', { name: consentTitle })

      await expect(onboarding.landing).toBeVisible()
      await expect(consent).toHaveCount(0)
      await shoot(page, 'F11a-tour-holds-card')

      await onboarding.landingSkipButton.click()
      await expect(onboarding.landing).toHaveCount(0)
      await expect(consent).toBeVisible()
      await expect.poll(() => readAutoShown(page)).toBe('true')
      await shoot(page, 'F11b-card-follows-tour')
    })
  })

  test.describe('F2 dismiss Getting Started: no card this session', () => {
    test.use({
      agentConsentAccepted: false,
      initialSettings: { 'Comfy.TutorialCompleted': false },
      initialFeatureFlags: {
        onboarding_tour_enabled: true,
        subscription_required: true
      }
    })
    test('capture', async ({ comfyPage }) => {
      const page = comfyPage.page
      await expect(
        page.getByRole('dialog', { name: gettingStartedTitle })
      ).toBeVisible()
      await page.getByTestId('getting-started-blank').click()
      await expect(
        page.getByRole('dialog', { name: gettingStartedTitle })
      ).toHaveCount(0)
      await expect(comfyPage.canvas).toBeVisible()
      await expect(
        page.getByRole('dialog', { name: consentTitle })
      ).toHaveCount(0)
      await shoot(page, 'F2-dismiss-no-card')
    })
  })

  test.describe('F14 Agent button opens the card any time', () => {
    test.use({ agentConsentAccepted: false })
    test('capture', async ({ comfyPage, agentPanel }) => {
      const page = comfyPage.page
      const consent = page.getByRole('dialog', { name: consentTitle })
      // Dismiss the automatic offer, then prove the button re-opens it.
      await expect(consent).toBeVisible()
      await consent
        .getByRole('button', { name: enMessages.agent.consent.reject })
        .click()
      await expect(consent).toHaveCount(0)
      await agentPanel.openButton.click()
      await expect(consent).toBeVisible()
      await shoot(page, 'F14-agent-button-opens-card')
    })
  })
})
