#!/usr/bin/env node

/**
 * Checks that AI-context docs were updated since the last git tag.
 * Blocks publish if AGENTS.md or docs/ui-kit-for-agents.md were not touched.
 * Pass --skip-docs-check to bypass the check.
 */

import { execSync } from 'child_process';
import pc from 'picocolors';

const DOCS_FILES: string[] = ['AGENTS.md', 'docs/ui-kit-for-agents.md'];

function exec(cmd: string): string {
    try {
        return execSync(cmd, { encoding: 'utf-8' }).trim();
    } catch {
        return '';
    }
}

function getLastTag(): string | null {
    const tag = exec('git describe --tags --abbrev=0 2>/dev/null');
    return tag || null;
}

function getChangedFilesSinceTag(tag: string | null): string[] {
    const range = tag ? `${tag}..HEAD` : 'HEAD';
    const output = exec(`git diff --name-only ${range}`);
    return output ? output.split('\n').filter(Boolean) : [];
}

function getUncommittedChanges(): string[] {
    const output = exec('git status --short');
    return output
        ? output
              .split('\n')
              .filter(Boolean)
              .map((line) => line.slice(3).trim())
        : [];
}

if (process.argv.includes('--skip-docs-check')) {
    console.log(pc.yellow('[check-docs] Docs check skipped (--skip-docs-check)'));
    process.exit(0);
}

const lastTag = getLastTag();
const changedSinceTag = getChangedFilesSinceTag(lastTag);
const uncommitted = getUncommittedChanges();
const allChanged = [...new Set([...changedSinceTag, ...uncommitted])];

const notUpdated = DOCS_FILES.filter((f) => !allChanged.includes(f));

if (notUpdated.length > 0) {
    console.error('');
    console.error(pc.red('[check-docs] PUBLISH BLOCKED: AI docs not updated!'));
    console.error('');
    console.error(pc.red('Files not changed since last tag:'));
    notUpdated.forEach((f) => console.error(pc.red(`  - ${f}`)));
    console.error('');
    console.error(pc.yellow('Update these files to reflect the changes in the new version.'));
    console.error(pc.yellow('If docs update is not needed, run with flag:'));
    console.error(pc.cyan('  npm run publish:npm:skip-docs'));
    console.error('');
    process.exit(1);
}

console.log(pc.green('[check-docs] AI docs are up to date. Publish allowed.'));
