const { chromium } = require('playwright');
const path = require('path');

async function sendNote(text) {
  const browser = await chromium.launch({ headless: true });
  const authPath = path.join(__dirname, 'auth.json');
  const logPath = path.join(__dirname, '..', 'logs', 'error_debug.png');
  
  const context = await browser.newContext({ storageState: authPath });
  const page = await context.newPage();
  
  // Increasing default timeout to 60s to handle self-hosted lag
  page.setDefaultTimeout(60000);
  await page.setViewportSize({ width: 1280, height: 1000 });

  try {
    const targetUrl = 'http://myaff.duckdns.org:3010/workspace/fc2caf2b-3e3e-48cc-9533-4eb63b4753cf/M5HIySO_xVmitXRc3ZjdQ';
    
    console.log('Opening AFFiNE...');
    // Reverting to domcontentloaded - safer than commit for your logic
    await page.goto(targetUrl, { waitUntil: 'domcontentloaded' });
    
    // Ensure the app shell is actually there
    await page.waitForSelector('#app');
    
    console.log('Syncing (15s)...');
    await page.waitForTimeout(15000); 

    // Focus top of editor - YOUR ORIGINAL FIX
    await page.mouse.click(640, 300); 
    await page.waitForTimeout(500);

    // Navigate to Absolute Top
    await page.keyboard.press('Meta+ArrowUp');
    await page.waitForTimeout(500);
    
    // Create new line at the very top and move into it
    await page.keyboard.press('Enter');
    await page.keyboard.press('ArrowUp'); 
    await page.waitForTimeout(1000);

    const dateStr = new Date().toLocaleString('en-CA', { 
        dateStyle: 'medium', 
        timeStyle: 'short' 
    });

    console.log('Injecting note units...');

    // Header line
    await page.keyboard.type('NOTE: ' + dateStr);
    await page.keyboard.press('Enter'); // Franco's separation fix
    
    // Soft Break
    await page.keyboard.down('Shift');
    await page.keyboard.press('Enter');
    await page.keyboard.up('Shift');

    // Content body
    await page.keyboard.type(text);
    
    // Soft Break
    await page.keyboard.down('Shift');
    await page.keyboard.press('Enter');
    await page.keyboard.up('Shift');

    // Divider line
    await page.keyboard.type('..........................................');

    // Final hard enter
    await page.keyboard.press('Enter');

    console.log('Finalizing sync (8s)...');
    await page.waitForTimeout(8000); 
    console.log('--- Success ---');

  } catch (err) {
    console.error('Execution Error:', err.message);
    await page.screenshot({ path: logPath });
  } finally {
    await browser.close();
  }
}

const nt = process.argv[2];
if (nt) {
    sendNote(nt).catch(err => {
        console.error("Fatal Error:", err);
        process.exit(1);
    });
}