# Debugging Download Detection

This guide helps you debug why PDF download detection may not be working.

## Prerequisites

1. **Rebuild and reload the extension**
   ```bash
   npm run build
   ```
   Then go to `chrome://extensions/` and click the reload icon for BinectChrome

2. **Open the Service Worker console**
   - Go to `chrome://extensions/`
   - Find BinectChrome
   - Click "service worker" link (or "Inspect views: service worker")
   - This opens DevTools for the service worker
   - **Keep this window open** while testing

## Step-by-Step Download Detection Test

### Step 1: Verify Service Worker is Running

**In the Service Worker console, you should see:**
```
[Service Worker] ===== BinectChrome service worker loaded =====
[Service Worker] Timestamp: 2024-01-14T...
[Service Worker] Initializing PDF detection...
[PDF Detector] Starting PDF detection, registering download listener
[PDF Detector] Listener registered successfully
```

**If you don't see these messages:**
- The service worker hasn't loaded yet
- Try clicking the extension icon (this wakes it up)
- Check for any red errors in the console

### Step 2: Test with a Simple PDF Download

**Download a test PDF:**
1. Right-click this link and select "Save link as...":
   ```
   https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf
   ```
2. Save it to your Downloads folder
3. Watch the Service Worker console

**Expected console output:**
```
[PDF Detector] Download changed: {id: 123, state: {...}, stateValue: "in_progress"}
[PDF Detector] Download not complete, ignoring
[PDF Detector] Download changed: {id: 123, state: {...}, stateValue: "complete"}
[PDF Detector] Download complete, searching for item: 123
[PDF Detector] Search results: 1 items
[PDF Detector] Download item: {id: 123, filename: "dummy.pdf", mime: "application/pdf", ...}
[PDF Detector] PDF detected!
[Service Worker] PDF DETECTED CALLBACK: dummy.pdf
[Service Worker] Badge updated, PDF stored in memory
```

**After successful detection:**
- Extension badge should show "1"
- Badge color should be blue (#4A90E2)

### Step 3: Test with Direct Link Download

**Alternative method:**
1. Paste this URL directly in the address bar:
   ```
   https://www.africau.edu/images/default/sample.pdf
   ```
2. Chrome will start downloading it
3. Watch the Service Worker console for the same log messages

### Step 4: Verify PDF is Stored

**Click the extension icon to open the popup**
- You should see the PDF details
- Filename: "dummy.pdf" or "sample.pdf"
- Size: displayed in KB or MB
- Domain: source domain
- "Send PDF to Binect" button should be enabled

## Troubleshooting: No Logs Appearing

### Issue 1: Service Worker Not Running
**Symptoms:** No console output at all, even "[Service Worker] loaded" message

**Solutions:**
1. **Wake up the service worker:**
   - Click the extension icon
   - OR go to `chrome://serviceworker-internals/` and find BinectChrome
   - Click "Start" if it's stopped

2. **Check for startup errors:**
   - Look for red errors in the service worker console
   - Check `chrome://serviceworker-internals/` for registration errors

3. **Hard reload the extension:**
   - Go to `chrome://extensions/`
   - Remove BinectChrome completely
   - Click "Load unpacked" and select the `dist/` folder again

### Issue 2: Service Worker Sleeping Before Download Completes
**Symptoms:** Service worker console shows "loaded" message, but no download events

**This is the most likely issue!** In Manifest V3, service workers shut down after 30 seconds of inactivity.

**Test if this is the issue:**
1. Open service worker console
2. Click the extension icon to wake it up
3. **Immediately** (within 30 seconds) download a PDF
4. Watch the console

**If you see logs now, the issue is service worker lifecycle!**

**Solution:** The service worker should automatically wake up when downloads complete, but there might be a timing issue. See "Potential Fixes" below.

### Issue 3: Download Events Not Firing
**Symptoms:** Service worker is running, but no "[PDF Detector] Download changed" logs

**Possible causes:**
1. **Downloads permission not granted:**
   - Go to `chrome://extensions/`
   - Click "Details" on BinectChrome
   - Check "Permissions" section
   - Should show "Read your browsing history" and "Manage your downloads"
   - If missing, the manifest is wrong

2. **Event listener not registered:**
   - Look for "[PDF Detector] Listener registered successfully" in console
   - If missing, there's a code issue

3. **Chrome not triggering download events:**
   - Try opening the PDF instead of downloading it (should trigger viewer detection)
   - Check `chrome://downloads/` to verify download completed

### Issue 4: PDF Not Detected (Logs Show It's Not a PDF)
**Symptoms:** Logs show "Not a PDF, ignoring"

**Debug the detection logic:**

Look at the download item log:
```
[PDF Detector] Download item: {
  id: 123,
  filename: "document.pdf",  // ← Should end with .pdf
  mime: "application/pdf",    // ← Should be "application/pdf"
  ...
}
```

**If filename doesn't end with .pdf and mime is not "application/pdf":**
- The file isn't actually a PDF
- OR the server sent wrong headers

## Advanced Debugging

### Check Download API Directly

**Run this in the Service Worker console:**
```javascript
chrome.downloads.search({ limit: 10, orderBy: ['-startTime'] }, (items) => {
  console.log('Recent downloads:', items);
  items.forEach(item => {
    console.log(`${item.filename} - mime: ${item.mime} - state: ${item.state}`);
  });
});
```

This shows your recent downloads and their properties.

### Manual Test: Trigger Detection Manually

**Run this in the Service Worker console:**
```javascript
// Get the most recent download
chrome.downloads.search({ limit: 1, orderBy: ['-startTime'] }, (items) => {
  if (items.length > 0) {
    const item = items[0];
    console.log('Most recent download:', item);

    // Check if it's a PDF
    const isPDF = item.filename.toLowerCase().endsWith('.pdf') || item.mime === 'application/pdf';
    console.log('Is PDF?', isPDF);
  }
});
```

### Check if Listener is Registered

**Run this in the Service Worker console:**
```javascript
// This won't show listeners directly, but you can test by downloading a file
console.log('Testing listener by downloading a test file...');
chrome.downloads.download({
  url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
  filename: 'test-binect.pdf'
}, (downloadId) => {
  console.log('Download started with ID:', downloadId);
});
```

Watch for "[PDF Detector] Download changed" logs.

## Potential Fixes

If download detection is unreliable due to service worker lifecycle:

### Option 1: Use chrome.storage for Persistence
Store detected PDFs in chrome.storage instead of memory, so they survive service worker restarts.

### Option 2: Add Download Completion Listener
Use `chrome.downloads.onCreated` in addition to `onChanged` to catch downloads earlier.

### Option 3: Poll Recent Downloads
When popup opens, check recent downloads even if callback didn't fire.

## Testing Different PDF Sources

### Test 1: Direct PDF Link
```
https://www.africau.edu/images/default/sample.pdf
```
**Expected:** Direct download, should detect

### Test 2: PDF Behind Link
```
https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf
```
**Expected:** Right-click → Save as, should detect

### Test 3: Large PDF
```
https://www.adobe.com/support/products/enterprise/knowledgecenter/media/c4611_sample_explain.pdf
```
**Expected:** Larger file, may take longer to download

### Test 4: Google Drive PDF
1. Upload a PDF to your Google Drive
2. Click it to view
3. **Important:** Use the PDF viewer detection (new feature)
4. If you download it, should also detect

## Success Criteria

**Download detection is working when:**
1. ✅ Service worker console shows all log messages
2. ✅ Badge updates to "1" after download
3. ✅ Popup shows PDF details
4. ✅ "Send PDF to Binect" button is enabled
5. ✅ Works consistently across multiple downloads

## Still Not Working?

If download detection still doesn't work after following this guide:

1. **Export debug logs:**
   - Right-click in service worker console → "Save as..."
   - Save the console output

2. **Check service worker status:**
   - Go to `chrome://serviceworker-internals/`
   - Find BinectChrome
   - Screenshot the status section

3. **Get downloads permission status:**
   ```javascript
   chrome.permissions.contains({
     permissions: ['downloads']
   }, (result) => {
     console.log('Has downloads permission:', result);
   });
   ```

4. **Report the issue:**
   - Email bernd.worsch@binect.de
   - Include: console logs, screenshots, Chrome version
   - Describe: what you tried, what happened

## Workaround: Use PDF Viewer Detection

**If download detection is unreliable, use the new PDF viewer detection:**
1. Open a PDF in Chrome (paste URL in address bar)
2. Click the extension icon
3. Should detect the PDF from the current tab
4. This bypasses download detection entirely!

See `TESTING_PDF_VIEWER.md` for details.
