"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.getArchitectureScoreBadgeColorName = getArchitectureScoreBadgeColorName;
exports.buildArchitectureScoreBadgeUrl = buildArchitectureScoreBadgeUrl;
exports.renderArchitectureScoreBadgeSvg = renderArchitectureScoreBadgeSvg;
exports.writeArchitectureScoreBadge = writeArchitectureScoreBadge;
exports.publishArchitectureScoreBadge = publishArchitectureScoreBadge;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const canonicalBadgeRelativePath = '.archpilot/badges/architecture-score.svg';
const publishedBadgeRelativePath = 'badges/architecture-score.svg';
const badgeLabel = 'ArchPilot Score';
const badgeColors = {
    brightgreen: '#4c1',
    green: '#97ca00',
    yellow: '#dfb317',
    orange: '#fe7d37',
    red: '#e05d44',
};
function resolveBadgePaths(workspaceRoot) {
    return {
        canonicalBadgePath: path.join(workspaceRoot, ...canonicalBadgeRelativePath.split('/')),
        publishedBadgePath: path.join(workspaceRoot, ...publishedBadgeRelativePath.split('/')),
    };
}
async function readLatestArchitectureScore(workspaceRoot) {
    const candidatePaths = [
        path.join(workspaceRoot, '.archpilot', 'validation-status.json'),
        path.join(workspaceRoot, '.archpilot', 'reports', 'architecture-summary.json'),
    ];
    for (const candidatePath of candidatePaths) {
        let raw;
        try {
            raw = await node_fs_1.promises.readFile(candidatePath, { encoding: 'utf8' });
        }
        catch {
            continue;
        }
        try {
            const parsed = JSON.parse(raw);
            const score = typeof parsed.summary?.healthScore === 'number' && Number.isFinite(parsed.summary.healthScore)
                ? parsed.summary.healthScore
                : typeof parsed.healthScore === 'number' && Number.isFinite(parsed.healthScore)
                    ? parsed.healthScore
                    : undefined;
            if (score !== undefined) {
                return score;
            }
        }
        catch {
            continue;
        }
    }
    return undefined;
}
function getArchitectureScoreBadgeColorName(score) {
    if (score >= 90) {
        return 'brightgreen';
    }
    if (score >= 75) {
        return 'green';
    }
    if (score >= 60) {
        return 'yellow';
    }
    if (score >= 45) {
        return 'orange';
    }
    return 'red';
}
function getBadgeColor(score) {
    return badgeColors[getArchitectureScoreBadgeColorName(score)];
}
function buildArchitectureScoreBadgeUrl(score) {
    const clampedScore = Math.max(0, Math.min(100, Math.round(score)));
    const color = getArchitectureScoreBadgeColorName(clampedScore);
    return `https://img.shields.io/badge/${encodeURIComponent(badgeLabel)}-${clampedScore}-${color}?style=flat-square`;
}
function escapeXml(value) {
    return value
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&apos;');
}
function renderArchitectureScoreBadgeSvg(score) {
    const clampedScore = Math.max(0, Math.min(100, Math.round(score)));
    const value = String(clampedScore);
    const labelWidth = 104;
    const valueWidth = Math.max(28, 10 + value.length * 8);
    const totalWidth = labelWidth + valueWidth;
    const color = getBadgeColor(clampedScore);
    const labelTextX = Math.round(labelWidth / 2);
    const valueTextX = Math.round(labelWidth + valueWidth / 2);
    return `<svg xmlns="http://www.w3.org/2000/svg" width="${totalWidth}" height="20" role="img" aria-label="${escapeXml(badgeLabel)}: ${escapeXml(value)}">
  <linearGradient id="smooth" x2="0" y2="100%">
    <stop offset="0" stop-color="#fff" stop-opacity=".1"/>
    <stop offset="1" stop-opacity=".1"/>
  </linearGradient>
  <clipPath id="round">
    <rect width="${totalWidth}" height="20"/>
  </clipPath>
  <g clip-path="url(#round)">
  <rect width="${labelWidth}" height="20" fill="#555"/>
  <rect x="${labelWidth}" width="${valueWidth}" height="20" fill="${color}"/>
  <rect width="${totalWidth}" height="20" fill="url(#smooth)"/>
  </g>
  <g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
    <text x="${labelTextX}" y="15" fill="#010101" fill-opacity=".3">${escapeXml(badgeLabel)}</text>
    <text x="${labelTextX}" y="14">${escapeXml(badgeLabel)}</text>
    <text x="${valueTextX}" y="15" fill="#010101" fill-opacity=".3">${escapeXml(value)}</text>
    <text x="${valueTextX}" y="14">${escapeXml(value)}</text>
  </g>
</svg>
`;
}
async function writeArchitectureScoreBadge(workspaceRoot, score) {
    const { canonicalBadgePath } = resolveBadgePaths(workspaceRoot);
    await node_fs_1.promises.mkdir(path.dirname(canonicalBadgePath), { recursive: true });
    await node_fs_1.promises.writeFile(canonicalBadgePath, renderArchitectureScoreBadgeSvg(score), {
        encoding: 'utf8',
    });
    await publishArchitectureScoreBadge(workspaceRoot);
    return canonicalBadgePath;
}
async function publishArchitectureScoreBadge(workspaceRoot) {
    const { canonicalBadgePath, publishedBadgePath } = resolveBadgePaths(workspaceRoot);
    const latestScore = await readLatestArchitectureScore(workspaceRoot);
    if (latestScore !== undefined) {
        await node_fs_1.promises.mkdir(path.dirname(canonicalBadgePath), { recursive: true });
        await node_fs_1.promises.writeFile(canonicalBadgePath, renderArchitectureScoreBadgeSvg(latestScore), {
            encoding: 'utf8',
        });
    }
    await node_fs_1.promises.access(canonicalBadgePath);
    await node_fs_1.promises.mkdir(path.dirname(publishedBadgePath), { recursive: true });
    await node_fs_1.promises.copyFile(canonicalBadgePath, publishedBadgePath);
    return {
        canonicalBadgePath,
        publishedBadgePath,
    };
}
//# sourceMappingURL=architectureScoreBadge.js.map