"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_test_1 = require("node:test");
const strict_1 = __importDefault(require("node:assert/strict"));
const node_child_process_1 = require("node:child_process");
const fs = __importStar(require("node:fs"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const github_1 = require("../github");
const run_1 = require("../commands/run");
const init_1 = require("../commands/init");
function gitCmd(args, cwd) {
    const result = (0, node_child_process_1.spawnSync)('git', args, { cwd, encoding: 'utf8' });
    if (result.status !== 0) {
        throw new Error(`git ${args.join(' ')} failed: ${result.stderr}`);
    }
}
function initRepo(dir) {
    gitCmd(['init', '-b', 'main'], dir);
    gitCmd(['config', 'user.email', 'test@test.com'], dir);
    gitCmd(['config', 'user.name', 'Test'], dir);
    fs.writeFileSync(path.join(dir, 'README.md'), '# test\n');
    gitCmd(['add', '.'], dir);
    gitCmd(['commit', '-m', 'initial commit'], dir);
}
// ─── getRemoteUrl ────────────────────────────────────────────────────────────
(0, node_test_1.describe)('getRemoteUrl', () => {
    let tmpDir;
    let originalCwd;
    (0, node_test_1.beforeEach)(() => {
        originalCwd = process.cwd();
        tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'aidev-gh-test-'));
        initRepo(tmpDir);
        process.chdir(tmpDir);
    });
    (0, node_test_1.afterEach)(() => {
        process.chdir(originalCwd);
        fs.rmSync(tmpDir, { recursive: true, force: true });
    });
    (0, node_test_1.it)('returns the remote URL for a valid remote', () => {
        gitCmd(['remote', 'add', 'origin', 'https://github.com/owner/repo.git'], tmpDir);
        strict_1.default.equal((0, github_1.getRemoteUrl)('origin'), 'https://github.com/owner/repo.git');
    });
    (0, node_test_1.it)('returns empty string for a nonexistent remote', () => {
        strict_1.default.equal((0, github_1.getRemoteUrl)('nonexistent'), '');
    });
    (0, node_test_1.it)('returns SSH URL for SSH remotes', () => {
        gitCmd(['remote', 'add', 'origin', 'git@github.com:owner/repo.git'], tmpDir);
        strict_1.default.equal((0, github_1.getRemoteUrl)('origin'), 'git@github.com:owner/repo.git');
    });
});
// ─── isGitHubRemote ──────────────────────────────────────────────────────────
(0, node_test_1.describe)('isGitHubRemote', () => {
    let tmpDir;
    let originalCwd;
    (0, node_test_1.beforeEach)(() => {
        originalCwd = process.cwd();
        tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'aidev-gh-test-'));
        initRepo(tmpDir);
        process.chdir(tmpDir);
    });
    (0, node_test_1.afterEach)(() => {
        process.chdir(originalCwd);
        fs.rmSync(tmpDir, { recursive: true, force: true });
    });
    (0, node_test_1.it)('returns true for HTTPS GitHub remote', () => {
        gitCmd(['remote', 'add', 'origin', 'https://github.com/owner/repo.git'], tmpDir);
        strict_1.default.equal((0, github_1.isGitHubRemote)('origin'), true);
    });
    (0, node_test_1.it)('returns true for SSH GitHub remote', () => {
        gitCmd(['remote', 'add', 'origin', 'git@github.com:owner/repo.git'], tmpDir);
        strict_1.default.equal((0, github_1.isGitHubRemote)('origin'), true);
    });
    (0, node_test_1.it)('returns false for non-GitHub remote', () => {
        gitCmd(['remote', 'add', 'origin', 'https://gitlab.com/owner/repo.git'], tmpDir);
        strict_1.default.equal((0, github_1.isGitHubRemote)('origin'), false);
    });
    (0, node_test_1.it)('returns false for nonexistent remote', () => {
        strict_1.default.equal((0, github_1.isGitHubRemote)('nonexistent'), false);
    });
});
// ─── isGhInstalled ───────────────────────────────────────────────────────────
(0, node_test_1.describe)('isGhInstalled', () => {
    (0, node_test_1.it)('returns a boolean', () => {
        const result = (0, github_1.isGhInstalled)();
        strict_1.default.equal(typeof result, 'boolean');
    });
});
// ─── getPullRequestMergeability ──────────────────────────────────────────────
(0, node_test_1.describe)('getPullRequestMergeability', () => {
    let tmpDir;
    let originalCwd;
    (0, node_test_1.beforeEach)(() => {
        originalCwd = process.cwd();
        tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'aidev-gh-test-'));
        initRepo(tmpDir);
        process.chdir(tmpDir);
    });
    (0, node_test_1.afterEach)(() => {
        process.chdir(originalCwd);
        fs.rmSync(tmpDir, { recursive: true, force: true });
    });
    (0, node_test_1.it)('returns UNKNOWN when there is no PR for the branch (gh exits non-zero)', () => {
        const value = (0, github_1.getPullRequestMergeability)('does-not-exist');
        strict_1.default.equal(value, 'UNKNOWN');
    });
});
// ─── tryCreatePR ─────────────────────────────────────────────────────────────
(0, node_test_1.describe)('tryCreatePR', () => {
    let tmpDir;
    let originalCwd;
    const baseConfig = {
        gitRemote: 'origin',
        githubBaseBranch: 'main',
        githubRepo: 'owner/repo',
        clickupInReviewStatus: 'review',
    };
    const task = {
        id: 'abc123',
        name: 'Fix bug',
        description: 'Fix the login bug',
        status: 'open',
        url: 'https://app.clickup.com/t/abc123',
        tags: ['myproject'],
    };
    (0, node_test_1.beforeEach)(() => {
        originalCwd = process.cwd();
        tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'aidev-gh-test-'));
        initRepo(tmpDir);
        process.chdir(tmpDir);
    });
    (0, node_test_1.afterEach)(() => {
        process.chdir(originalCwd);
        fs.rmSync(tmpDir, { recursive: true, force: true });
    });
    (0, node_test_1.it)('falls back to compare URL when remote is not GitHub', () => {
        gitCmd(['remote', 'add', 'origin', 'https://gitlab.com/owner/repo.git'], tmpDir);
        const url = (0, run_1.tryCreatePR)(baseConfig, 'abc123/fix-bug', task);
        strict_1.default.ok(url.includes('github.com/owner/repo/compare/'));
    });
    (0, node_test_1.it)('falls back to compare URL when no remote exists', () => {
        const url = (0, run_1.tryCreatePR)(baseConfig, 'abc123/fix-bug', task);
        strict_1.default.ok(url.includes('github.com/owner/repo/compare/'));
    });
    (0, node_test_1.it)('returns empty string when githubRepo is not configured and gh is not available', () => {
        const url = (0, run_1.tryCreatePR)({ ...baseConfig, githubRepo: '' }, 'abc123/fix-bug', task);
        strict_1.default.equal(url, '');
    });
});
// ─── printGhSuggestion ──────────────────────────────────────────────────────
(0, node_test_1.describe)('printGhSuggestion', () => {
    let tmpDir;
    let originalCwd;
    (0, node_test_1.beforeEach)(() => {
        originalCwd = process.cwd();
        tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'aidev-gh-test-'));
        initRepo(tmpDir);
        process.chdir(tmpDir);
    });
    (0, node_test_1.afterEach)(() => {
        process.chdir(originalCwd);
        fs.rmSync(tmpDir, { recursive: true, force: true });
    });
    (0, node_test_1.it)('does not print anything for non-GitHub remotes', () => {
        gitCmd(['remote', 'add', 'origin', 'https://gitlab.com/owner/repo.git'], tmpDir);
        const logs = [];
        const origLog = console.log;
        console.log = (...args) => { logs.push(args.join(' ')); };
        try {
            (0, init_1.printGhSuggestion)('origin');
            strict_1.default.equal(logs.length, 0);
        }
        finally {
            console.log = origLog;
        }
    });
    (0, node_test_1.it)('prints suggestion for GitHub remote', () => {
        gitCmd(['remote', 'add', 'origin', 'https://github.com/owner/repo.git'], tmpDir);
        const logs = [];
        const origLog = console.log;
        console.log = (...args) => { logs.push(args.join(' ')); };
        try {
            (0, init_1.printGhSuggestion)('origin');
            const output = logs.join('\n');
            strict_1.default.ok(output.includes('gh'));
        }
        finally {
            console.log = origLog;
        }
    });
});
// ─── filterUnresolvedByNonAidev ─────────────────────────────────────────────
(0, node_test_1.describe)('filterUnresolvedByNonAidev', () => {
    const prefix = '🤖 **aidev**';
    const makeThread = (id, comments) => ({
        id,
        path: 'src/index.ts',
        line: 1,
        comments,
    });
    (0, node_test_1.it)('keeps threads where last comment is not from aidev', () => {
        const threads = [
            makeThread('t1', [
                { body: 'Please fix this', author: 'reviewer' },
            ]),
        ];
        const result = (0, github_1.filterUnresolvedByNonAidev)(threads, prefix);
        strict_1.default.equal(result.length, 1);
        strict_1.default.equal(result[0].id, 't1');
    });
    (0, node_test_1.it)('filters out threads where last comment starts with commentPrefix', () => {
        const threads = [
            makeThread('t1', [
                { body: 'Please fix this', author: 'reviewer' },
                { body: `${prefix} I've fixed this in commit abc123`, author: 'aidev-bot' },
            ]),
        ];
        const result = (0, github_1.filterUnresolvedByNonAidev)(threads, prefix);
        strict_1.default.equal(result.length, 0);
    });
    (0, node_test_1.it)('keeps threads where aidev commented but a human replied after', () => {
        const threads = [
            makeThread('t1', [
                { body: 'Please fix this', author: 'reviewer' },
                { body: `${prefix} Done`, author: 'aidev-bot' },
                { body: 'Actually this is still wrong', author: 'reviewer' },
            ]),
        ];
        const result = (0, github_1.filterUnresolvedByNonAidev)(threads, prefix);
        strict_1.default.equal(result.length, 1);
    });
    (0, node_test_1.it)('returns empty array when all threads are aidev-last', () => {
        const threads = [
            makeThread('t1', [{ body: `${prefix} Fixed`, author: 'bot' }]),
            makeThread('t2', [{ body: `${prefix} Replied`, author: 'bot' }]),
        ];
        const result = (0, github_1.filterUnresolvedByNonAidev)(threads, prefix);
        strict_1.default.equal(result.length, 0);
    });
    (0, node_test_1.it)('keeps threads with no comments', () => {
        const threads = [makeThread('t1', [])];
        const result = (0, github_1.filterUnresolvedByNonAidev)(threads, prefix);
        strict_1.default.equal(result.length, 1);
    });
    (0, node_test_1.it)('handles mixed threads correctly', () => {
        const threads = [
            makeThread('t1', [{ body: 'Fix this', author: 'human' }]),
            makeThread('t2', [{ body: `${prefix} Done`, author: 'bot' }]),
            makeThread('t3', [{ body: 'Another issue', author: 'human' }]),
        ];
        const result = (0, github_1.filterUnresolvedByNonAidev)(threads, prefix);
        strict_1.default.equal(result.length, 2);
        strict_1.default.deepEqual(result.map((t) => t.id), ['t1', 't3']);
    });
});
//# sourceMappingURL=github.test.js.map