import { describe, expect, it } from 'vitest'

import {
  buildRuntimeReadinessReport,
  deriveHealthBaseUrl,
  fetchLiveAuthHealth,
  fetchLiveReleaseManifest,
  fetchLiveWebsiteShell,
  parseEnvFile,
} from './runtime-readiness-lib.mjs'

function createMockResponse({
  ok = true,
  status = 200,
  contentType = 'application/json',
  body = '',
} = {}) {
  return {
    ok,
    status,
    headers: {
      get(name) {
        if (String(name).toLowerCase() === 'content-type') {
          return contentType
        }
        return null
      },
    },
    async text() {
      return body
    },
  }
}

describe('parseEnvFile', () => {
  it('parses simple dotenv-style content with quotes and export prefixes', () => {
    const parsed = parseEnvFile(`
      # comment
      export API_DOMAIN="https://hypertwist.app"
      COOKIE_SECURE=true
      VITE_SUPPORT_EMAIL='hello@hypertwist.app'
    `)

    expect(parsed).toEqual({
      API_DOMAIN: 'https://hypertwist.app',
      COOKIE_SECURE: 'true',
      VITE_SUPPORT_EMAIL: 'hello@hypertwist.app',
    })
  })
})

describe('live deployment fetch helpers', () => {
  it('rejects placeholder HTML from the auth-health route with an explicit error', async () => {
    await expect(
      fetchLiveAuthHealth('https://hypertwist.app', async () => createMockResponse({
        contentType: 'text/html; charset=utf-8',
        body: `
          <!doctype html>
          <html>
            <head><title>HyperTwist</title></head>
            <body>
              <p>Deployment target is live on the new VPS. Application rollout is pending.</p>
            </body>
          </html>
        `,
      })),
    ).rejects.toThrow(/placeholder rollout page/i)
  })

  it('parses a valid anonymous public release manifest', async () => {
    const payload = await fetchLiveReleaseManifest('https://hypertwist.app', async () => createMockResponse({
      body: JSON.stringify({
        ok: true,
        manifest: {
          viewer: {
            authenticated: false,
            canDownload: false,
          },
          platforms: [
            {
              platform_key: 'windows',
              configured: true,
              download_url: null,
            },
          ],
        },
      }),
    }))

    expect(payload.manifest.viewer.authenticated).toBe(false)
    expect(payload.manifest.platforms[0].platform_key).toBe('windows')
  })

  it('detects the first-party shell marker and placeholder posture on the website root', async () => {
    const shell = await fetchLiveWebsiteShell('https://hypertwist.app', async () => createMockResponse({
      contentType: 'text/html; charset=utf-8',
      body: `
        <!doctype html>
        <html lang="en">
          <head>
            <title>HyperTwist</title>
            <meta name="hypertwist-site-shell" content="first-party-website-v1" />
          </head>
          <body>
            <div id="root"></div>
          </body>
        </html>
      `,
    }))

    expect(shell.title).toBe('HyperTwist')
    expect(shell.hasShellMarker).toBe(true)
    expect(shell.hasRootMount).toBe(true)
    expect(shell.placeholderDetected).toBe(false)
  })
})

describe('buildRuntimeReadinessReport', () => {
  it('passes a fully configured public same-origin posture', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_PUBLIC_DEPLOYMENT_TIER: 'launch',
        VITE_SUPERTOKENS_API_DOMAIN: 'https://hypertwist.app',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'https://hypertwist.app',
        VITE_AUTH_API_BASE_URL: 'https://hypertwist.app',
        VITE_WINDOWS_DOWNLOAD_URL: 'https://downloads.hypertwist.app/windows.exe',
        VITE_PADDLE_CHECKOUT_URL_OPERATOR: 'https://buy.paddle.com/operator',
        VITE_PADDLE_CHECKOUT_URL_STUDIO: 'https://buy.paddle.com/studio',
        VITE_MPL_SOURCE_URL: 'https://hypertwist.app/open-source/source',
        VITE_OPEN_SOURCE_REPO_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      },
      serverEnv: {
        DEPLOYMENT_TIER: 'launch',
        API_DOMAIN: 'https://hypertwist.app',
        WEBSITE_DOMAIN: 'https://hypertwist.app',
        SUPERTOKENS_CORE_URI: 'https://auth-core.internal',
        COOKIE_SECURE: 'true',
        SERVE_STATIC_WEBSITE: 'true',
        PADDLE_WEBHOOK_SECRET: 'secret',
        PADDLE_PRICE_PLAN_MAP: '{"pri_operator":"operator"}',
      },
      liveHealth: {
        supertokens: { ready: true },
        fallback: { active: false },
        runtime: {
          public_origin_ready: true,
          mode: 'public',
          errors: [],
          warnings: [],
        },
        billing: {
          webhookSecretConfigured: true,
          productPlanMapConfigured: false,
          pricePlanMapConfigured: true,
        },
      },
    })

    expect(report.ok).toBe(true)
    expect(report.failures).toEqual([])
  })

  it('accepts preview deployment posture with missing checkout, download, and webhook values', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_PUBLIC_DEPLOYMENT_TIER: 'preview',
        VITE_SUPERTOKENS_API_DOMAIN: 'https://hypertwist.app',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'https://hypertwist.app',
        VITE_AUTH_API_BASE_URL: 'https://hypertwist.app',
        VITE_MPL_SOURCE_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
        VITE_OPEN_SOURCE_REPO_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      },
      serverEnv: {
        DEPLOYMENT_TIER: 'preview',
        API_DOMAIN: 'https://hypertwist.app',
        WEBSITE_DOMAIN: 'https://hypertwist.app',
        SUPERTOKENS_CORE_URI: 'http://127.0.0.1:3567',
        COOKIE_SECURE: 'true',
      },
      liveHealth: {
        supertokens: { ready: true },
        fallback: { active: false },
        runtime: {
          public_origin_ready: true,
          mode: 'mixed',
          errors: [],
          warnings: ['SUPERTOKENS_CORE_URI still targets a loopback/local-development host.'],
        },
        billing: {
          webhookSecretConfigured: false,
          productPlanMapConfigured: false,
          pricePlanMapConfigured: false,
        },
      },
    })

    expect(report.ok).toBe(true)
    expect(report.failures).toEqual([])
    expect(report.warnings).toContain('VITE_WINDOWS_DOWNLOAD_URL or WINDOWS_DOWNLOAD_URL is not set; Windows download will remain in preview posture until the release lane is configured.')
    expect(report.warnings).toContain('VITE_PADDLE_CHECKOUT_URL_OPERATOR is not set; Operator pricing will stay on the support fallback until checkout is configured.')
    expect(report.warnings).toContain('PADDLE_WEBHOOK_SECRET is not set; billing webhook handling will remain in preview posture until the live secret is configured.')
    expect(report.warnings).toContain('Live runtime warning: SUPERTOKENS_CORE_URI still targets a loopback/local-development host.')
  })

  it('warns when same-origin public posture leaves static website serving ambiguous', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_SUPERTOKENS_API_DOMAIN: 'https://hypertwist.app',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'https://hypertwist.app',
        VITE_AUTH_API_BASE_URL: 'https://hypertwist.app',
        VITE_WINDOWS_DOWNLOAD_URL: 'https://downloads.hypertwist.app/windows.exe',
        VITE_PADDLE_CHECKOUT_URL_OPERATOR: 'https://buy.paddle.com/operator',
        VITE_MPL_SOURCE_URL: 'https://hypertwist.app/open-source/source',
        VITE_OPEN_SOURCE_REPO_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      },
      serverEnv: {
        API_DOMAIN: 'https://hypertwist.app',
        WEBSITE_DOMAIN: 'https://hypertwist.app',
        SUPERTOKENS_CORE_URI: 'https://auth-core.internal',
        COOKIE_SECURE: 'true',
        PADDLE_WEBHOOK_SECRET: 'secret',
        PADDLE_PRICE_PLAN_MAP: '{"pri_operator":"operator"}',
      },
      liveHealth: null,
    })

    expect(report.warnings).toContain('SERVE_STATIC_WEBSITE is not explicitly set; confirm ../dist is present for first-party same-origin serving or that an external same-origin web server serves the frontend.')
  })

  it('fails localhost-grade posture and missing public-launch configuration', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_SUPERTOKENS_API_DOMAIN: 'http://localhost:3001',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'http://localhost:4273',
        VITE_AUTH_API_BASE_URL: 'http://localhost:3001',
      },
      serverEnv: {
        API_DOMAIN: 'http://localhost:3001',
        WEBSITE_DOMAIN: 'http://localhost:4273',
        SUPERTOKENS_CORE_URI: 'http://localhost:3567',
        COOKIE_SECURE: 'false',
      },
      liveHealth: null,
    })

    expect(report.ok).toBe(false)
    expect(report.failures).toContain('VITE_SUPERTOKENS_API_DOMAIN still targets a loopback/local-development origin.')
    expect(report.failures).toContain('COOKIE_SECURE must be true before public launch.')
    expect(report.failures).toContain('PADDLE_WEBHOOK_SECRET is missing.')
  })

  it('fails placeholder values even when production-shaped env files are otherwise populated', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_SUPERTOKENS_API_DOMAIN: 'https://hypertwist.app',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'https://hypertwist.app',
        VITE_AUTH_API_BASE_URL: 'https://hypertwist.app',
        VITE_WINDOWS_DOWNLOAD_URL: 'https://downloads.hypertwist.app/replace-me/windows.exe',
        VITE_PADDLE_CHECKOUT_URL_OPERATOR: 'https://buy.paddle.com/replace-me-operator',
        VITE_PADDLE_CHECKOUT_URL_STUDIO: 'https://buy.paddle.com/replace-me-studio',
        VITE_MPL_SOURCE_URL: 'https://hypertwist.app/open-source/replace-me',
        VITE_OPEN_SOURCE_REPO_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      },
      serverEnv: {
        API_DOMAIN: 'https://hypertwist.app',
        WEBSITE_DOMAIN: 'https://hypertwist.app',
        SUPERTOKENS_CORE_URI: 'http://127.0.0.1:3567',
        COOKIE_SECURE: 'true',
        PADDLE_WEBHOOK_SECRET: 'replace-me-paddle-webhook-secret',
        PADDLE_PRICE_PLAN_MAP: '{"replace_me_price_operator":"operator"}',
      },
      liveHealth: null,
    })

    expect(report.ok).toBe(false)
    expect(report.failures).toContain('VITE_WINDOWS_DOWNLOAD_URL still contains a placeholder value.')
    expect(report.failures).toContain('VITE_PADDLE_CHECKOUT_URL_OPERATOR still contains a placeholder value.')
    expect(report.failures).toContain('PADDLE_WEBHOOK_SECRET still contains a placeholder value.')
    expect(report.failures).toContain('PADDLE_PRICE_PLAN_MAP still contains a placeholder value.')
  })

  it('still fails placeholder commercial values during preview posture', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_PUBLIC_DEPLOYMENT_TIER: 'preview',
        VITE_SUPERTOKENS_API_DOMAIN: 'https://hypertwist.app',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'https://hypertwist.app',
        VITE_AUTH_API_BASE_URL: 'https://hypertwist.app',
        VITE_WINDOWS_DOWNLOAD_URL: 'https://downloads.hypertwist.app/replace-me/windows.exe',
        VITE_PADDLE_CHECKOUT_URL_OPERATOR: 'https://buy.paddle.com/replace-me-operator',
        VITE_MPL_SOURCE_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
        VITE_OPEN_SOURCE_REPO_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      },
      serverEnv: {
        DEPLOYMENT_TIER: 'preview',
        API_DOMAIN: 'https://hypertwist.app',
        WEBSITE_DOMAIN: 'https://hypertwist.app',
        SUPERTOKENS_CORE_URI: 'http://127.0.0.1:3567',
        COOKIE_SECURE: 'true',
        PADDLE_WEBHOOK_SECRET: 'replace-me-paddle-webhook-secret',
      },
      liveHealth: null,
    })

    expect(report.ok).toBe(false)
    expect(report.failures).toContain('VITE_WINDOWS_DOWNLOAD_URL still contains a placeholder value.')
    expect(report.failures).toContain('VITE_PADDLE_CHECKOUT_URL_OPERATOR still contains a placeholder value.')
    expect(report.failures).toContain('PADDLE_WEBHOOK_SECRET still contains a placeholder value.')
  })

  it('accepts server-backed release-manifest download and source posture when frontend fallback URLs are absent', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_SUPERTOKENS_API_DOMAIN: 'https://hypertwist.app',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'https://hypertwist.app',
        VITE_AUTH_API_BASE_URL: 'https://hypertwist.app',
        VITE_PADDLE_CHECKOUT_URL_OPERATOR: 'https://buy.paddle.com/operator',
        VITE_PADDLE_CHECKOUT_URL_STUDIO: 'https://buy.paddle.com/studio',
      },
      serverEnv: {
        API_DOMAIN: 'https://hypertwist.app',
        WEBSITE_DOMAIN: 'https://hypertwist.app',
        SUPERTOKENS_CORE_URI: 'https://auth-core.internal',
        COOKIE_SECURE: 'true',
        PADDLE_WEBHOOK_SECRET: 'secret',
        PADDLE_PRICE_PLAN_MAP: '{"pri_operator":"operator"}',
        WINDOWS_DOWNLOAD_URL: 'https://downloads.hypertwist.app/windows.exe',
        MPL_SOURCE_URL: 'https://hypertwist.app/open-source/source',
        OPEN_SOURCE_REPO_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      },
      liveHealth: {
        supertokens: { ready: true },
        fallback: { active: false },
        runtime: {
          public_origin_ready: true,
          mode: 'public',
          errors: [],
          warnings: [],
        },
        billing: {
          webhookSecretConfigured: true,
          productPlanMapConfigured: false,
          pricePlanMapConfigured: true,
        },
      },
    })

    expect(report.ok).toBe(true)
    expect(report.failures).toEqual([])
  })

  it('fails live deployment checks when the public manifest leaks URLs or the root page is still placeholder-backed', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_SUPERTOKENS_API_DOMAIN: 'https://hypertwist.app',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'https://hypertwist.app',
        VITE_AUTH_API_BASE_URL: 'https://hypertwist.app',
        VITE_PADDLE_CHECKOUT_URL_OPERATOR: 'https://buy.paddle.com/operator',
        VITE_MPL_SOURCE_URL: 'https://hypertwist.app/open-source/source',
        VITE_OPEN_SOURCE_REPO_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
        VITE_WINDOWS_DOWNLOAD_URL: 'https://downloads.hypertwist.app/windows.exe',
      },
      serverEnv: {
        API_DOMAIN: 'https://hypertwist.app',
        WEBSITE_DOMAIN: 'https://hypertwist.app',
        SUPERTOKENS_CORE_URI: 'https://auth-core.internal',
        COOKIE_SECURE: 'true',
        PADDLE_WEBHOOK_SECRET: 'secret',
        PADDLE_PRICE_PLAN_MAP: '{"pri_operator":"operator"}',
      },
      liveHealth: {
        supertokens: { ready: true },
        fallback: { active: false },
        runtime: {
          public_origin_ready: true,
          mode: 'public',
          errors: [],
          warnings: [],
        },
        billing: {
          webhookSecretConfigured: true,
          productPlanMapConfigured: false,
          pricePlanMapConfigured: true,
        },
      },
      liveReleaseManifest: {
        ok: true,
        manifest: {
          viewer: {
            authenticated: false,
            canDownload: false,
          },
          platforms: [
            {
              platform_key: 'windows',
              configured: true,
              download_url: 'https://downloads.hypertwist.app/windows.exe',
            },
          ],
        },
      },
      liveWebsiteShell: {
        title: 'HyperTwist',
        hasShellMarker: false,
        hasRootMount: false,
        placeholderDetected: true,
      },
      liveHealthAttempted: true,
      liveReleaseManifestAttempted: true,
      liveWebsiteShellAttempted: true,
    })

    expect(report.ok).toBe(false)
    expect(report.failures).toContain('Live public release manifest exposes a raw download URL to anonymous viewers.')
    expect(report.failures).toContain('Live website root still serves the placeholder rollout page instead of the first-party HyperTwist shell.')
    expect(report.failures).toContain('Live website root is missing the first-party HyperTwist shell marker.')
    expect(report.failures).toContain('Live website root is missing the expected #root app mount.')
  })

  it('fails when the live release manifest drifts from the configured launch authority', () => {
    const report = buildRuntimeReadinessReport({
      frontendEnv: {
        VITE_SUPPORT_EMAIL: 'ops@hypertwist.app',
        VITE_PUBLIC_DOCS_URL: 'https://docs.hypertwist.app',
        VITE_RELEASE_NOTES_URL: 'https://notes.hypertwist.app',
        VITE_SUPERTOKENS_API_DOMAIN: 'https://hypertwist.app',
        VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'https://hypertwist.app',
        VITE_AUTH_API_BASE_URL: 'https://hypertwist.app',
        VITE_PADDLE_CHECKOUT_URL_OPERATOR: 'https://buy.paddle.com/operator-live',
        VITE_PADDLE_CHECKOUT_URL_STUDIO: 'https://buy.paddle.com/studio-live',
        VITE_PLAN_PRICE_OPERATOR: '$19 / month',
        VITE_PLAN_PRICE_STUDIO: '$99 / month',
        VITE_MPL_SOURCE_URL: 'https://hypertwist.app/open-source/source.zip',
        VITE_OPEN_SOURCE_REPO_URL: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
        VITE_WINDOWS_DOWNLOAD_URL: 'https://downloads.hypertwist.app/windows.exe',
      },
      serverEnv: {
        API_DOMAIN: 'https://hypertwist.app',
        WEBSITE_DOMAIN: 'https://hypertwist.app',
        SUPERTOKENS_CORE_URI: 'https://auth-core.internal',
        COOKIE_SECURE: 'true',
        PADDLE_WEBHOOK_SECRET: 'secret',
        PADDLE_PRICE_PLAN_MAP: '{"pri_operator":"operator"}',
        RELEASE_MANIFEST_VERSION: '1.0.0',
        RELEASE_MANIFEST_CHANNEL: 'candidate',
        WINDOWS_RELEASE_BUILD_ID: 'win64-1000',
        WINDOWS_RELEASE_SHA256: 'abc123',
        WINDOWS_RELEASE_FILE_SIZE_BYTES: '1048576',
      },
      liveHealth: {
        supertokens: { ready: true },
        fallback: { active: false },
        runtime: {
          public_origin_ready: true,
          mode: 'public',
          errors: [],
          warnings: [],
        },
        billing: {
          webhookSecretConfigured: true,
          productPlanMapConfigured: false,
          pricePlanMapConfigured: true,
        },
      },
      liveReleaseManifest: {
        ok: true,
        manifest: {
          support_email: 'hello@hypertwist.app',
          public_docs_url: 'https://old-docs.hypertwist.app',
          release_notes_url: 'https://notes.hypertwist.app',
          corresponding_source_url: 'https://hypertwist.app/open-source/source.zip',
          open_source_repo_url: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
          commerce: {
            operator_checkout_url: 'https://buy.paddle.com/operator-old',
            studio_checkout_url: 'https://buy.paddle.com/studio-live',
            plan_price_operator: '$29 / month',
            plan_price_studio: '$99 / month',
          },
          viewer: {
            authenticated: false,
            canDownload: false,
          },
          platforms: [
            {
              platform_key: 'windows',
              configured: false,
              channel: 'preview',
              version: '0.9.0',
              build_id: 'old-build',
              published_at: null,
              file_name: null,
              file_size_bytes: 512,
              checksum_sha256: 'stale',
              download_url: null,
            },
            {
              platform_key: 'macos',
              configured: false,
              channel: 'preview',
              version: null,
              build_id: null,
              published_at: null,
              file_name: null,
              file_size_bytes: null,
              checksum_sha256: null,
              download_url: null,
            },
            {
              platform_key: 'linux',
              configured: false,
              channel: 'preview',
              version: null,
              build_id: null,
              published_at: null,
              file_name: null,
              file_size_bytes: null,
              checksum_sha256: null,
              download_url: null,
            },
          ],
        },
      },
      liveReleaseManifestAttempted: true,
      liveHealthAttempted: true,
    })

    expect(report.ok).toBe(false)
    expect(report.failures).toContain('Live release manifest support email drifted from configured launch authority (expected ops@hypertwist.app, got hello@hypertwist.app).')
    expect(report.failures).toContain('Live release manifest public docs URL drifted from configured launch authority (expected https://docs.hypertwist.app, got https://old-docs.hypertwist.app).')
    expect(report.failures).toContain('Live release manifest operator checkout URL drifted from configured launch authority (expected https://buy.paddle.com/operator-live, got https://buy.paddle.com/operator-old).')
    expect(report.failures).toContain('Live release manifest operator price string drifted from configured launch authority (expected $19 / month, got $29 / month).')
    expect(report.failures).toContain('Live release manifest Windows configured posture drifted from configured launch authority (expected true, got false).')
    expect(report.failures).toContain('Live release manifest Windows release channel drifted from configured launch authority (expected candidate, got preview).')
    expect(report.failures).toContain('Live release manifest Windows release version drifted from configured launch authority (expected 1.0.0, got 0.9.0).')
    expect(report.failures).toContain('Live release manifest Windows release build ID drifted from configured launch authority (expected win64-1000, got old-build).')
    expect(report.failures).toContain('Live release manifest Windows release file size drifted from configured launch authority (expected 1048576, got 512).')
    expect(report.failures).toContain('Live release manifest Windows release checksum drifted from configured launch authority (expected abc123, got stale).')
  })
})

describe('deriveHealthBaseUrl', () => {
  it('prefers the explicit health URL over env-derived defaults', () => {
    const baseUrl = deriveHealthBaseUrl({
      explicitHealthUrl: 'https://hypertwist.app/',
      frontendEnv: {
        VITE_AUTH_API_BASE_URL: 'https://auth.hypertwist.app',
      },
      serverEnv: {
        API_DOMAIN: 'https://server.hypertwist.app',
      },
    })

    expect(baseUrl).toBe('https://hypertwist.app')
  })
})
