import path from 'node:path'

import { logBrowserSessionDebug } from './session-login-shared.js'

type BrowserPageLike = {
  screenshot: (options: { path: string; fullPage?: boolean }) => Promise<unknown>
}

type ReviewSession = {
  sessionId: string
  loginType: string
  sessionDir: string
  page: BrowserPageLike
  lastReview?: {
    screenshotPath?: string
    signature?: string
    [key: string]: unknown
  } | null
}

type ActivityInfoForReview = {
  role?: {
    roleId?: string
    roleName?: string
  }
}

export function resolveReviewSignature(session: Pick<ReviewSession, 'loginType'>, activityInfo: ActivityInfoForReview) {
  const roleId = String(activityInfo?.role?.roleId || '').trim()
  const roleName = String(activityInfo?.role?.roleName || '').trim()

  return {
    roleId,
    roleName,
    signature: `${session.loginType}|${roleId}|${roleName}`,
  }
}

export async function ensureReviewScreenshot(session: ReviewSession, activityInfo: ActivityInfoForReview): Promise<boolean> {
  const { roleId, roleName, signature } = resolveReviewSignature(session, activityInfo)

  if (session.lastReview?.screenshotPath && session.lastReview?.signature === signature) {
    return false
  }

  const screenshotPath = path.join(session.sessionDir, 'role-review.png')

  try {
    await session.page.screenshot({
      path: screenshotPath,
      fullPage: true,
    })
    session.lastReview = {
      screenshotPath,
      capturedAt: new Date().toISOString(),
      roleId,
      roleName,
      signature,
    }
    return true
  } catch (error) {
    logBrowserSessionDebug('reviewScreenshot.capture.error', {
      sessionId: session.sessionId,
      message: error instanceof Error ? error.message : String(error),
    })
    return false
  }
}
