// =============================================
// sp-comms.js — Pidgey Assist: Communication Layer
// Content script messaging, security guards, tab helpers.
// =============================================

// ======== SECURITY HELPERS ========
export function isRestrictedUrl(url) {
    if (!url) return false;
    const lower = url.toLowerCase();
    const sensitive = ['paypal.com', 'chase.com', 'bankofamerica.com', 'wellsfargo.com', 'fidelity.com', 'mychart', 'vanguard.com', 'schwab.com', 'citi.com', 'capitalone.com'];
    return sensitive.some(domain => lower.includes(domain));
}

export function redactPII(text) {
    if (!text || typeof text !== 'string') return text;
    let safe = text.replace(/\b(?:\d[ -]*?){13,16}\b/g, '[REDACTED_CC]');
    safe = safe.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[REDACTED_SSN]');
    return safe;
}

// ======== TAB HELPER ========
export function waitForTabLoad(tabId) {
    return new Promise((resolve) => {
        const listener = (id, info) => {
            if (id === tabId && info.status === 'complete') {
                chrome.tabs.onUpdated.removeListener(listener);
                setTimeout(resolve, 500); // Brief settle time for JS to init
            }
        };
        chrome.tabs.onUpdated.addListener(listener);
        setTimeout(resolve, 8000); // Safety timeout
    });
}

// ======== CONTENT SCRIPT MESSENGER ========
// Probes whether a content script is live before sending, and auto-injects if not.
export async function sendToContentScript(message, tabId = null) {
    return new Promise((resolve) => {
        const sendReq = (tid) => {
            chrome.tabs.get(tid, (tab) => {
                if (chrome.runtime.lastError || !tab) {
                    resolve('Error: Tab not found.');
                    return;
                }
                if (!tab.url || (
                    tab.url.startsWith('chrome://') ||
                    tab.url.startsWith('chrome-extension://') ||
                    tab.url.startsWith('edge://') ||
                    tab.url.startsWith('about:') ||
                    tab.url.startsWith('https://chrome.google.com/webstore') ||
                    tab.url.startsWith('https://chromewebstore.google.com') ||
                    tab.url === 'chrome://newtab/' ||
                    tab.url === 'about:newtab'
                )) {
                    resolve('Chirp! I cannot read browser-internal or new-tab pages!');
                    return;
                }
                if (isRestrictedUrl(tab.url)) {
                    resolve('Chirp! Security Policy: I am not allowed to interact with or read secure financial/medical portals.');
                    return;
                }

                const doSend = () => {
                    chrome.tabs.sendMessage(tid, message, (response) => {
                        if (chrome.runtime.lastError) {
                            resolve(`Chirp! Connection to tab lost. Error: ${chrome.runtime.lastError.message}. If this is a background tab, ensure you enabled "Global Tab Access" in Settings.`);
                        } else {
                            let textResp = response || 'done';
                            if (typeof textResp === 'string') {
                                textResp = redactPII(textResp);
                            } else if (typeof textResp === 'object') {
                                try { textResp = JSON.parse(redactPII(JSON.stringify(textResp))); } catch { }
                            }
                            resolve(textResp);
                        }
                    });
                };

                // Probe first — auto-inject content.js if not loaded yet (e.g. fresh tab)
                chrome.tabs.sendMessage(tid, { type: 'PIDGEY_PING' }, () => {
                    if (chrome.runtime.lastError) {
                        chrome.scripting.executeScript(
                            { target: { tabId: tid }, files: ['content.js'] },
                            () => {
                                if (chrome.runtime.lastError) {
                                    resolve(`Chirp! I couldn't access that tab. Error: ${chrome.runtime.lastError.message}. If it's a background tab, you might need to enable **Global Tab Access** (God Mode) in Settings.`);
                                } else {
                                    setTimeout(doSend, 300);
                                }
                            }
                        );
                    } else {
                        doSend();
                    }
                });
            });
        };

        if (tabId) {
            sendReq(tabId);
        } else {
            chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
                if (!tabs[0]?.id) { resolve('No active tab'); return; }
                sendReq(tabs[0].id);
            });
        }
    });
}

// ======== BROADCAST TO ALL TABS ========
export function notifyContentScript(state) {
    chrome.tabs.query({}, (tabs) => {
        for (const tab of tabs) {
            if (tab.id && tab.url && !tab.url.startsWith('chrome://')) {
                chrome.tabs.sendMessage(tab.id, { type: 'PIDGEY_STATE', state }).catch(() => { });
            }
        }
    });
}
