// src/engine/reflection/drift-detect.ts
//
// Compares the `forked_from_commit` frontmatter of a custom piece against the
// latest commit that touched the corresponding built-in file.
//
// Returns { drifted: false } in all no-op cases:
//   - custom file does not exist (not forked yet)
//   - built-in file does not exist
//   - custom file has no forked_from_commit in frontmatter
//   - git is unavailable (no .git/, git not installed)
//
// When both commits are known and differ, drifted = true.

import { execSync } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import matter from 'gray-matter';

export interface DriftStatus {
  drifted: boolean;
  forkedFromCommit: string | null;
  latestCommit: string | null;
}

export function detectDrift(customPath: string, builtinPath: string): DriftStatus {
  // Neither path exists → nothing to compare.
  if (!existsSync(customPath) || !existsSync(builtinPath)) {
    return { drifted: false, forkedFromCommit: null, latestCommit: null };
  }

  // Read forked_from_commit from custom YAML frontmatter.
  const parsed = matter(readFileSync(customPath, 'utf-8'));
  const forkedFromCommit = (parsed.data.forked_from_commit as string | undefined) ?? null;

  // Query git for the latest commit that touched the built-in file.
  let latestCommit: string | null = null;
  try {
    const out = execSync(
      `git log -1 --format=%H -- ${JSON.stringify(builtinPath)}`,
      { encoding: 'utf-8' }
    ).trim();
    latestCommit = out || null;
  } catch {
    // Not a git checkout, git not installed, or path not tracked — graceful no-op.
  }

  // If either commit is missing we cannot determine drift.
  if (!forkedFromCommit || !latestCommit) {
    return { drifted: false, forkedFromCommit, latestCommit };
  }

  return {
    drifted: forkedFromCommit !== latestCommit,
    forkedFromCommit,
    latestCommit,
  };
}
