import fetch from 'node-fetch';

// In-memory state to track "recent" activity polls so we don't spam duplicate logs
const lastCheckTimestamps = {
    figma: {},
    github: {}
};

export function attachExternalBridges(app) {
    console.log("🌉 Initializing External MCP Bridges (Figma, GitHub)...");

    // ==========================================
    // FIGMA MCP BRIDGE
    // ==========================================
    app.post('/api/bridge/figma', async (req, res) => {
        const { fileKey, token } = req.query;
        if (!fileKey || !token) {
            return res.json(mcpError("Missing 'fileKey' or 'token' query parameters."));
        }

        const { params } = req.body;
        const toolName = params?.name;
        let resultText = "No data returned.";

        try {
            const headers = { 'X-Figma-Token': token };

            if (toolName === "get_initial_state") {
 const response = await fetch(`https://api.figma.com/v1/files/${fileKey}`, { headers });

                if (!response.ok) throw new Error("Figma API rejected request.");
                const data = await response.json();
                
                resultText = `Figma Environment Boot State:\n- File Name: ${data.name}\n- Last Modified: ${data.lastModified}\n- Version: ${data.version}`;
                lastCheckTimestamps.figma[fileKey] = new Date().toISOString();
            } 
            else if (toolName === "get_recent_activity") {
                // Fetch file comments to track design collaboration activity
                const response = await fetch(`https://api.figma.com/v1/files/${fileKey}/comments`, { headers });
                const data = await response.json();
                
                const lastCheck = lastCheckTimestamps.figma[fileKey] || new Date(Date.now() - 3600000).toISOString(); // Default to last 1 hour
                const newComments = (data.comments ||[]).filter(c => new Date(c.created_at) > new Date(lastCheck));

                if (newComments.length > 0) {
                    resultText = newComments.map(c => `[Figma Comment by ${c.user.handle}]: ${c.message}`).join("\n");
                } else {
                    resultText = "No new activity";
                }
                lastCheckTimestamps.figma[fileKey] = new Date().toISOString();
            }
            else if (toolName === "get_hierarchy") {
                const response = await fetch(`https://api.figma.com/v1/files/${fileKey}?depth=1`, { headers });
                const data = await response.json();
                
                const pages = data.document.children.map(p => `- Page: ${p.name}`).join("\n");
                resultText = `Figma Document Hierarchy:\n${pages}`;
            }

            res.json(mcpSuccess(resultText));
        } catch (e) {
            res.json(mcpSuccess(`Figma Bridge Error: ${e.message}`));
        }
    });

    // ==========================================
    // GITHUB MCP BRIDGE
    // ==========================================
    app.post('/api/bridge/github', async (req, res) => {
        const { repo, token } = req.query; // repo format: "owner/repo"
        if (!repo || !token) {
            return res.json(mcpError("Missing 'repo' or 'token' query parameters."));
        }

        const { params } = req.body;
        const toolName = params?.name;
        let resultText = "No data returned.";

        try {
            const headers = { 
                'Authorization': `token ${token}`,
                'Accept': 'application/vnd.github.v3+json',
                'User-Agent': 'Thrust-MCP-Bridge'
            };

            if (toolName === "get_initial_state") {
                const response = await fetch(`https://api.github.com/repos/${repo}`, { headers });
                if (!response.ok) throw new Error("GitHub API rejected request.");
                const data = await response.json();
                
                resultText = `GitHub Repository Boot State:\n- Repo: ${data.full_name}\n- Default Branch: ${data.default_branch}\n- Open Issues: ${data.open_issues_count}\n- Updated At: ${data.updated_at}`;
                lastCheckTimestamps.github[repo] = new Date().toISOString();
            } 
            else if (toolName === "get_recent_activity") {
                // Fetch repository events (pushes, issues, PRs)
                const response = await fetch(`https://api.github.com/repos/${repo}/events?per_page=10`, { headers });
                const data = await response.json();
                
                const lastCheck = lastCheckTimestamps.github[repo] || new Date(Date.now() - 3600000).toISOString();
                const newEvents = (data ||[]).filter(e => new Date(e.created_at) > new Date(lastCheck));

                if (newEvents.length > 0) {
                    resultText = newEvents.map(e => `[GitHub ${e.type} by ${e.actor.login}]: ${formatGithubEvent(e)}`).join("\n");
                } else {
                    resultText = "No new activity";
                }
                lastCheckTimestamps.github[repo] = new Date().toISOString();
            }
            else if (toolName === "get_properties") {
                // Use targetArg to fetch issue details. Example target: "issue/12"
                const target = params?.arguments?.target || "";
                if (target.startsWith("issue/")) {
                    const issueNumber = target.split("/")[1];
                    const response = await fetch(`https://api.github.com/repos/${repo}/issues/${issueNumber}`, { headers });
                    const data = await response.json();
                    resultText = `Issue #${data.number}: ${data.title}\nState: ${data.state}\nBody: ${data.body}`;
                } else {
                    resultText = "Unsupported GitHub property target. Try 'issue/123'.";
                }
            }

            res.json(mcpSuccess(resultText));
        } catch (e) {
            res.json(mcpSuccess(`GitHub Bridge Error: ${e.message}`));
        }
    });

    // Helper to format raw GitHub events into readable Timeline strings
    function formatGithubEvent(e) {
        if (e.type === "PushEvent") return `Pushed ${e.payload.commits?.length || 0} commits to ${e.payload.ref}`;
        if (e.type === "IssuesEvent") return `${e.payload.action} issue #${e.payload.issue.number} - "${e.payload.issue.title}"`;
        if (e.type === "PullRequestEvent") return `${e.payload.action} PR #${e.payload.pull_request.number} - "${e.payload.pull_request.title}"`;
        if (e.type === "IssueCommentEvent") return `Commented on issue #${e.payload.issue.number}`;
        return `Triggered ${e.type}`;
    }

    function mcpSuccess(text) {
        return { jsonrpc: "2.0", result: { content: [{ type: "text", text }] } };
    }

    function mcpError(errorMsg) {
        return { jsonrpc: "2.0", error: { code: -32602, message: errorMsg } };
    }
}
