import { expect, test } from '@playwright/test';
import { Wallet } from 'ethers';
import { createWalletContext } from '../../setup/wallet-provider';
import { getStackConfig, validateStackHealthy } from '../../setup/stack';
import {
  createReport,
  connectWallet,
  mintEth,
  buyKrk,
  takeScreenshot,
  logObservation,
  logCopyFeedback,
  logTokenomicsQuestion,
  recordPageVisit,
  recordAction,
  writeReport,
  attemptStake,
  resetChainState,
} from './helpers';

// Priya uses Anvil account #4
const ACCOUNT_PRIVATE_KEY = '0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a';
const ACCOUNT_ADDRESS = new Wallet(ACCOUNT_PRIVATE_KEY).address.toLowerCase();

const STACK_CONFIG = getStackConfig();
const STACK_RPC_URL = STACK_CONFIG.rpcUrl;
const STACK_WEBAPP_URL = STACK_CONFIG.webAppUrl;

test.describe('Dr. Priya Malhotra - Institutional/Analytical Investor', () => {
  test.beforeAll(async () => {
    await resetChainState(STACK_RPC_URL);
    await validateStackHealthy(STACK_CONFIG);
  });

  test('Priya analyzes Kraiken with academic rigor', async ({ browser }) => {
    const report = createReport('Dr. Priya Malhotra');
    const personaName = 'Priya';
    
    console.log(`[${personaName}] Starting test - Institutional investor evaluating mechanism design...`);
    
    const context = await createWalletContext(browser, {
      privateKey: ACCOUNT_PRIVATE_KEY,
      rpcUrl: STACK_RPC_URL,
    });
    
    const page = await context.newPage();
    page.on('console', msg => console.log(`[BROWSER] ${msg.type()}: ${msg.text()}`));
    page.on('pageerror', error => console.log(`[BROWSER ERROR] ${error.message}`));
    
    try {
      // --- Landing Page (Critical Analysis) ---
      let pageStart = Date.now();
      await page.goto(`${STACK_WEBAPP_URL}/app/`, { waitUntil: 'domcontentloaded' });
      // eslint-disable-next-line no-restricted-syntax -- waitForTimeout: no event source exists for animation settling, wallet connector UI transitions, and debounced state updates in user-simulation tests. See AGENTS.md #Engineering Principles.
      await page.waitForTimeout(2_000);
      
      await takeScreenshot(page, personaName, 'landing-page', report);
      logObservation(personaName, 'Initial assessment: Clean UI, but need to verify claims about mechanism design', report);
      logTokenomicsQuestion(personaName, 'What is the theoretical Nash equilibrium for tax rates in this Harberger tax system?', report);
      
      recordPageVisit('Landing', page.url(), pageStart, report);
      
      // --- Look for Technical Documentation ---
      logObservation(personaName, 'Searching for whitepaper, technical appendix, or formal specification...', report);
      
      const docsLink = await page.getByText(/docs|documentation|whitepaper|technical/i).isVisible().catch(() => false);
      
      if (!docsLink) {
        logCopyFeedback(personaName, 'No visible link to technical documentation. For institutional investors, this is essential.', report);
        logObservation(personaName, 'Would normally review GitHub repository and TECHNICAL_APPENDIX.md before proceeding', report);
      }
      
      await takeScreenshot(page, personaName, 'searching-for-docs', report);
      
      // --- Look for Audit Reports ---
      const auditLink = await page.getByText(/audit/i).isVisible().catch(() => false);
      
      if (!auditLink) {
        logCopyFeedback(personaName, 'No audit report link visible. Institutional capital requires multi-firm audits at minimum.', report);
        logTokenomicsQuestion(personaName, 'Has this undergone formal verification? Any peer-reviewed analysis of the mechanism?', report);
      } else {
        logObservation(personaName, 'Audit link found - would review full report before committing capital', report);
      }
      
      // --- Check for Governance Information ---
      logObservation(personaName, 'Looking for governance structure, DAO participation, or admin key disclosures...', report);
      
      const governanceLink = await page.getByText(/governance|dao/i).isVisible().catch(() => false);
      
      if (!governanceLink) {
        logTokenomicsQuestion(personaName, 'What are the centralization risks? Who holds admin keys? Is there a timelock?', report);
      }
      
      // --- Connect Wallet ---
      pageStart = Date.now();
      await connectWallet(page);
      await takeScreenshot(page, personaName, 'wallet-connected', report);
      recordAction('Connect wallet', true, undefined, report);
      logObservation(personaName, 'Wallet connected. Proceeding with empirical testing of mechanism claims.', report);
      
      // --- Examine Stake Page Statistics ---
      pageStart = Date.now();
      await page.goto(`${STACK_WEBAPP_URL}/app/stake`);
      // eslint-disable-next-line no-restricted-syntax -- waitForTimeout: no event source exists for animation settling, wallet connector UI transitions, and debounced state updates in user-simulation tests. See AGENTS.md #Engineering Principles.
      await page.waitForTimeout(3_000);
      recordPageVisit('Stake (analysis)', page.url(), pageStart, report);
      
      await takeScreenshot(page, personaName, 'stake-dashboard', report);
      logObservation(personaName, 'Analyzing statistics: Average tax rate, claimed slots, inflation metrics', report);
      logTokenomicsQuestion(personaName, 'Is the 7-day inflation rate sustainable long-term? What\'s the terminal supply?', report);
      
      // --- Examine Three-Position Liquidity Claim ---
      pageStart = Date.now();
      await page.goto(`${STACK_WEBAPP_URL}/app/cheats`);
      // eslint-disable-next-line no-restricted-syntax -- waitForTimeout: no event source exists for animation settling, wallet connector UI transitions, and debounced state updates in user-simulation tests. See AGENTS.md #Engineering Principles.
      await page.waitForTimeout(2_000);
      recordPageVisit('Cheats (liquidity analysis)', page.url(), pageStart, report);
      
      await takeScreenshot(page, personaName, 'liquidity-snapshot', report);
      logObservation(personaName, 'Examining liquidity snapshot to verify three-position VWAP defense mechanism', report);
      
      const liquidityTableVisible = await page.locator('.liquidity-table').isVisible().catch(() => false);
      
      if (liquidityTableVisible) {
        logObservation(personaName, 'Liquidity table visible - analyzing Floor/Anchor/Discovery positions', report);
        logTokenomicsQuestion(personaName, 'What prevents a sophisticated attacker from manipulating VWAP across multiple blocks?', report);
        logTokenomicsQuestion(personaName, 'Are the OptimizerV3 parameters (binary switch) based on theoretical modeling or empirical fuzzing?', report);
      } else {
        logCopyFeedback(personaName, 'Liquidity metrics not easily accessible - institutional investors need transparency', report);
      }
      
      // --- Test Buy Depth Calculation ---
      logObservation(personaName, 'Reviewing buy depth to discovery edge - critical for large position entry', report);
      
      const buyDepthVisible = await page.getByText(/buy depth/i).isVisible().catch(() => false);
      
      if (buyDepthVisible) {
        logTokenomicsQuestion(personaName, 'What is the maximum position size before significant slippage? Need liquidity depth analysis.', report);
      }
      
      // --- Mint ETH for Testing ---
      await mintEth(page, STACK_RPC_URL, ACCOUNT_ADDRESS, '100');
      recordAction('Mint 100 ETH', true, undefined, report);
      logObservation(personaName, 'Allocated test capital for mechanism verification', report);
      
      // --- Test Significant Swap Size ---
      logObservation(personaName, 'Testing swap with institutional-size allocation to measure slippage', report);
      
      try {
        await buyKrk(page, '10.0');
        recordAction('Buy KRK with 5.0 ETH (institutional test)', true, undefined, report);
        await takeScreenshot(page, personaName, 'large-swap-complete', report);
        logTokenomicsQuestion(personaName, 'Actual slippage on 5 ETH buy vs theoretical calculation - does three-position model hold?', report);
      } catch (error: any) {
        logObservation(personaName, `Large swap failed: ${error.message}. Liquidity depth insufficient for institutional size.`, report);
        recordAction('Buy KRK with 5.0 ETH', false, error.message, report);
      }
      
      // eslint-disable-next-line no-restricted-syntax -- waitForTimeout: no event source exists for animation settling, wallet connector UI transitions, and debounced state updates in user-simulation tests. See AGENTS.md #Engineering Principles.
      await page.waitForTimeout(3_000);
      
      // --- Navigate to Stake for Optimal Tax Rate Analysis ---
      pageStart = Date.now();
      await page.goto(`${STACK_WEBAPP_URL}/app/stake`);
      // eslint-disable-next-line no-restricted-syntax -- waitForTimeout: no event source exists for animation settling, wallet connector UI transitions, and debounced state updates in user-simulation tests. See AGENTS.md #Engineering Principles.
      await page.waitForTimeout(2_000);
      recordPageVisit('Stake (optimization)', page.url(), pageStart, report);
      
      await takeScreenshot(page, personaName, 'stake-form-analysis', report);
      logObservation(personaName, 'Analyzing tax rate options to determine optimal strategy based on game theory', report);
      logTokenomicsQuestion(personaName, 'Given current average tax rate, what is the rational choice for a large staker?', report);
      logTokenomicsQuestion(personaName, 'Does higher tax rate create sustainable moat or just reduce yield unnecessarily?', report);
      
      // --- Review Tax Rate Distribution ---
      const activePositionsSection = page.locator('.active-positions-wrapper');
      const positionsVisible = await activePositionsSection.isVisible().catch(() => false);
      
      if (positionsVisible) {
        logObservation(personaName, 'Examining distribution of active positions to identify equilibrium patterns', report);
        logTokenomicsQuestion(personaName, 'Are tax rates clustering around specific values? Suggests Nash equilibrium convergence.', report);
      }
      
      // --- Test Optimal Stake ---
      logObservation(personaName, 'Executing stake at calculated optimal tax rate (12% based on current average)', report);
      
      try {
        await attemptStake(page, '500', '12', personaName, report);
        await takeScreenshot(page, personaName, 'institutional-stake-success', report);
        logObservation(personaName, 'Stake executed successfully. Position size represents test allocation only.', report);
        recordAction('Stake 500 KRK at 12% tax (optimal)', true, undefined, report);
      } catch (error: any) {
        logObservation(personaName, `Stake failed: ${error.message}. Technical implementation issues detected.`, report);
        logCopyFeedback(personaName, 'Error handling needs improvement for production use', report);
        recordAction('Stake 500 KRK at 12% tax', false, error.message, report);
      }
      
      // eslint-disable-next-line no-restricted-syntax -- waitForTimeout: no event source exists for animation settling, wallet connector UI transitions, and debounced state updates in user-simulation tests. See AGENTS.md #Engineering Principles.
      await page.waitForTimeout(3_000);
      
      // --- Review Position Management Interface ---
      await page.goto(`${STACK_WEBAPP_URL}/app/stake`);
      // eslint-disable-next-line no-restricted-syntax -- waitForTimeout: no event source exists for animation settling, wallet connector UI transitions, and debounced state updates in user-simulation tests. See AGENTS.md #Engineering Principles.
      await page.waitForTimeout(2_000);
      await takeScreenshot(page, personaName, 'position-management', report);
      
      logObservation(personaName, 'Evaluating position management interface for institutional needs', report);
      logCopyFeedback(personaName, 'Need detailed position analytics: time-weighted APY, tax collected vs paid, snatch vulnerability score', report);
      logTokenomicsQuestion(personaName, 'What is the exit liquidity for large positions? Can I unstake without significant slippage?', report);
      
      // --- Risk Assessment ---
      logObservation(personaName, 'Conducting risk assessment: smart contract risk, liquidity risk, mechanism design risk', report);
      logTokenomicsQuestion(personaName, 'What is the worst-case scenario for a position holder? Need stress test data.', report);
      logCopyFeedback(personaName, 'Risk disclosure section needed: clearly state protocol assumptions and failure modes', report);
      
      // --- Composability Analysis ---
      logObservation(personaName, 'Evaluating potential for integration with other DeFi protocols', report);
      logTokenomicsQuestion(personaName, 'Can staked positions be tokenized for use in lending markets? Any ERC-721 wrapper planned?', report);
      logTokenomicsQuestion(personaName, 'How does this integrate with broader Base ecosystem? Cross-protocol synergies?', report);
      
      // --- Final Assessment ---
      // eslint-disable-next-line no-restricted-syntax -- waitForTimeout: no event source exists for animation settling, wallet connector UI transitions, and debounced state updates in user-simulation tests. See AGENTS.md #Engineering Principles.
      await page.waitForTimeout(2_000);
      await takeScreenshot(page, personaName, 'final-analysis', report);
      
      report.overallSentiment = 'Intellectually intriguing mechanism with sound theoretical basis, but several concerns for institutional deployment. STRENGTHS: Novel Harberger tax application, three-position liquidity defense shows theoretical sophistication, clean UI suggests professional team. CONCERNS: (1) OptimizerV3 binary switch lacks rigorous justification in visible documentation - appears empirically tuned rather than theoretically derived. (2) Insufficient liquidity depth for meaningful institutional positions (>$100k). (3) No formal verification or multi-firm audit visible. (4) Centralization risks not disclosed. (5) Long-term sustainability of inflation model unclear. VERDICT: Would allocate $50-100k for 3-6 month observation period to gather empirical data on Nash equilibrium convergence and three-position VWAP defense under real market conditions. Full institutional allocation ($500k+) would require: formal verification, multi-firm audits, governance transparency, liquidity depth >$5M, and 6-12 months of battle-testing. Recommendation for team: Publish academic paper on mechanism design, get formal verification, increase transparency around parameter selection, create institutional-grade documentation. This could be a flagship DeFi primitive if executed with full rigor.';
      
      logObservation(personaName, report.overallSentiment, report);
      
    } finally {
      writeReport('dr-priya-malhotra', report);
      await context.close();
    }
  });
});
