"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.runGithubPrCommentAdapter = runGithubPrCommentAdapter;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const https = __importStar(require("node:https"));
const githubInlineAnnotations_1 = require("./githubInlineAnnotations");
const reviewCommentMarker = '<!-- archpilot-pr-review -->';
const legacyReviewCommentMarker = '<!-- ARCHPILOT_REVIEW_COMMENT -->';
function requestGithubApi(options) {
    return new Promise((resolve, reject) => {
        const payload = options.body !== undefined ? JSON.stringify(options.body) : undefined;
        const request = https.request({
            hostname: 'api.github.com',
            path: options.path,
            method: options.method,
            headers: {
                Authorization: `Bearer ${options.token}`,
                'Content-Type': 'application/json',
                'User-Agent': 'archpilot-cli',
                Accept: 'application/vnd.github+json',
                ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
            },
        }, (response) => {
            const chunks = [];
            response.on('data', (chunk) => {
                chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
            });
            response.on('end', () => {
                resolve({
                    statusCode: response.statusCode ?? 0,
                    body: Buffer.concat(chunks).toString('utf8'),
                });
            });
        });
        request.on('error', reject);
        if (payload) {
            request.write(payload);
        }
        request.end();
    });
}
function parseRepository(value) {
    const segments = value.split('/');
    if (segments.length !== 2 || !segments[0] || !segments[1]) {
        return undefined;
    }
    return { owner: segments[0], repo: segments[1] };
}
function buildCommentBody(reviewMarkdown) {
    return `${reviewCommentMarker}
${reviewMarkdown.trimEnd()}

---

Generated by ArchPilot CI
`;
}
async function readReviewMarkdown(workspaceRoot) {
    const reviewPaths = [
        path.join(workspaceRoot, '.archpilot', 'reports', 'pr-architecture-review.md'),
        path.join(workspaceRoot, '.archpilot', 'reports', 'architecture-pr-review.md'),
    ];
    for (const reviewPath of reviewPaths) {
        try {
            return await node_fs_1.promises.readFile(reviewPath, { encoding: 'utf8' });
        }
        catch {
            continue;
        }
    }
    return undefined;
}
async function resolvePrNumber(eventPath) {
    try {
        const raw = await node_fs_1.promises.readFile(eventPath, { encoding: 'utf8' });
        const parsed = JSON.parse(raw);
        if (!parsed.pull_request || typeof parsed.pull_request.number !== 'number') {
            return undefined;
        }
        return parsed.pull_request.number;
    }
    catch {
        return undefined;
    }
}
async function runGithubPrCommentAdapter(workspaceRoot) {
    const annotationResult = await (0, githubInlineAnnotations_1.emitGithubInlineArchitectureAnnotations)(workspaceRoot);
    if (!annotationResult.reportFound) {
        console.log('ArchPilot inline annotations: no fresh report source found for this run; PR comment publication will continue.');
    }
    const reviewMarkdown = await readReviewMarkdown(workspaceRoot);
    if (!reviewMarkdown) {
        console.error('No architecture PR review report found.');
        console.error('Run:');
        console.error('archpilot review pr');
        return 1;
    }
    const token = process.env.GITHUB_TOKEN;
    const repository = process.env.GITHUB_REPOSITORY;
    const eventPath = process.env.GITHUB_EVENT_PATH;
    if (!token) {
        console.error('GITHUB_TOKEN is missing.');
        return 1;
    }
    if (!repository || !eventPath) {
        console.error('Not running inside GitHub Actions.');
        return 1;
    }
    const parsedRepository = parseRepository(repository);
    if (!parsedRepository) {
        console.error('GITHUB_REPOSITORY is invalid.');
        return 1;
    }
    const prNumber = await resolvePrNumber(eventPath);
    if (!prNumber) {
        console.error('GitHub PR context not detected.');
        return 0;
    }
    const commentBody = buildCommentBody(reviewMarkdown);
    const commentsPath = `/repos/${parsedRepository.owner}/${parsedRepository.repo}/issues/${prNumber}/comments`;
    let commentsResponse;
    try {
        commentsResponse = await requestGithubApi({
            token,
            method: 'GET',
            path: commentsPath,
        });
    }
    catch {
        console.error('GitHub API request failed while listing PR comments.');
        return 1;
    }
    if (commentsResponse.statusCode < 200 || commentsResponse.statusCode >= 300) {
        console.error('GitHub API request failed while listing PR comments.');
        return 1;
    }
    let comments = [];
    try {
        const parsed = JSON.parse(commentsResponse.body);
        if (Array.isArray(parsed)) {
            comments = parsed
                .filter((entry) => entry &&
                typeof entry === 'object' &&
                typeof entry.id === 'number' &&
                typeof entry.body === 'string')
                .map((entry) => entry);
        }
    }
    catch {
        console.error('GitHub API returned invalid comments payload.');
        return 1;
    }
    const existingComment = comments
        .filter((comment) => comment.body.includes(reviewCommentMarker) ||
        comment.body.includes(legacyReviewCommentMarker))
        .sort((left, right) => left.id - right.id)[0];
    if (existingComment) {
        let updateResponse;
        try {
            updateResponse = await requestGithubApi({
                token,
                method: 'PATCH',
                path: `/repos/${parsedRepository.owner}/${parsedRepository.repo}/issues/comments/${existingComment.id}`,
                body: { body: commentBody },
            });
        }
        catch {
            console.error('GitHub API request failed while updating PR comment.');
            return 1;
        }
        if (updateResponse.statusCode < 200 || updateResponse.statusCode >= 300) {
            console.error('GitHub API request failed while updating PR comment.');
            return 1;
        }
        console.log('ArchPilot PR review comment updated.');
        return 0;
    }
    let createResponse;
    try {
        createResponse = await requestGithubApi({
            token,
            method: 'POST',
            path: commentsPath,
            body: { body: commentBody },
        });
    }
    catch {
        console.error('GitHub API request failed while creating PR comment.');
        return 1;
    }
    if (createResponse.statusCode < 200 || createResponse.statusCode >= 300) {
        console.error('GitHub API request failed while creating PR comment.');
        return 1;
    }
    console.log('ArchPilot PR review comment posted.');
    return 0;
}
//# sourceMappingURL=githubPrCommentAdapter.js.map