const GitUtils = require('../utils/git');
const SymlinkUtils = require('../utils/symlinks');
const UI = require('../utils/ui');
const fs = require('fs');
const path = require('path');

// Lightweight semver compare. Returns positive if a > b, negative if a < b,
// zero if equal. Treats malformed input as 0 — degrade open rather than throw.
function cmpSemver(a, b) {
  if (!a || !b) return 0;
  const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0);
  const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0);
  for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
    const d = (pa[i] || 0) - (pb[i] || 0);
    if (d !== 0) return d;
  }
  return 0;
}

async function status() {
  const git = new GitUtils();
  const symlinks = new SymlinkUtils();

  try {
    UI.header('BALDART STATUS');

    // Check installation
    const exists = await git.frameworkExists();

    if (!exists) {
      UI.warning('Framework not installed');
      UI.info('Install with: npx baldart add');
      process.exit(0);
    }

    // Get version
    const version = await git.getFrameworkVersion();
    UI.success(`Framework installed: v${version}`);

    // Check symlinks
    UI.newline();
    UI.section('Symlinks Status');
    const symlinkValid = symlinks.verifySymlinks();

    if (!symlinkValid) {
      UI.newline();
      UI.warning('Some symlinks are broken. Run: baldart add (to reinstall)');
    }

    // Check customizable files
    UI.newline();
    UI.section('Customizable Files');

    const customFiles = [
      '.claude/hooks/lint-before-commit.sh.template',
      '.claude/hooks/lint-before-commit.sh',
      'docs/references/ui-guidelines.template.md',
      'docs/references/brand-guidelines.md',
      'templates/feature-card.template.yml',
      'baldart.config.yml',
    ];

    customFiles.forEach(file => {
      const fullPath = path.join(process.cwd(), file);
      if (fs.existsSync(fullPath)) {
        UI.success(`Found: ${file}`);
      } else {
        UI.warning(`Missing: ${file}`);
      }
    });

    // Project context (v3.0.0+): list any authored skill overlays
    UI.newline();
    UI.section('Skill Overlays (.baldart/overlays/)');

    const overlaysDir = path.join(process.cwd(), '.baldart', 'overlays');
    if (!fs.existsSync(overlaysDir)) {
      UI.warning('Missing: .baldart/overlays/ — run `npx baldart configure` to create it.');
    } else {
      const overlays = fs.readdirSync(overlaysDir).filter((f) => f.endsWith('.md'));
      if (overlays.length === 0) {
        UI.info('No overlays authored. Examples in: .framework/templates/overlays/');
      } else {
        // Best-effort drift check — SHA-first (mirrors `overlay drift`): the
        // pinned base_file_sha is the source of truth; an overlay is drifted
        // only when the base SKILL.md content actually changed. Version is a
        // fallback ONLY when base_file_sha is absent, since VERSION bumps every
        // release regardless of whether THIS base changed (v4.11.0).
        const yaml = require('js-yaml');
        const fwVersion = version;
        let computeBaseFileSha;
        try { ({ computeBaseFileSha } = require('../utils/overlay-merger')); }
        catch (_) { computeBaseFileSha = null; }
        overlays.forEach((file) => {
          const full = path.join(overlaysDir, file);
          let line = `Overlay: ${file}`;
          try {
            const txt = fs.readFileSync(full, 'utf8');
            const fmMatch = txt.match(/^---\n([\s\S]*?)\n---/);
            if (fmMatch) {
              const fm = yaml.load(fmMatch[1]) || {};
              const name = file.replace(/\.md$/, '');
              const baseAbs = path.join(process.cwd(), '.framework', 'framework', '.claude', 'skills', name, 'SKILL.md');
              // SHA-first when we can read the base file.
              if (fm.base_file_sha && computeBaseFileSha && fs.existsSync(baseAbs)) {
                const currentSha = computeBaseFileSha(fs.readFileSync(baseAbs, 'utf8'));
                if (String(fm.base_file_sha) !== currentSha) {
                  line += ` (base changed: sha ${fm.base_file_sha} → ${currentSha} — review for drift)`;
                  UI.warning(line);
                  return;
                }
                if (fm.base_skill_version) line += ` (v${fm.base_skill_version}, base unchanged)`;
                UI.success(line);
                return;
              }
              // Fallback: no base_file_sha → version comparison.
              if (fm.base_skill_version && fwVersion && fm.base_skill_version !== fwVersion) {
                line += ` (targets v${fm.base_skill_version}, installed v${fwVersion} — review for drift)`;
                UI.warning(line);
                return;
              }
              if (fm.base_skill_version) line += ` (v${fm.base_skill_version})`;
            }
            UI.success(line);
          } catch (_) {
            UI.warning(`${line} — could not parse frontmatter`);
          }
        });
      }
    }

    // Check for pending updates (since v3.17.1 — was a no-op stub before).
    UI.newline();
    UI.section('Update Status');

    let updateAvailable = false;
    let remoteVersion = null;
    try {
      await git.fetch('antbald/BALDART');
      remoteVersion = await git.getRemoteVersion('antbald/BALDART', 'main');
      if (!remoteVersion || remoteVersion === 'unknown') {
        UI.warning('Could not read remote VERSION — check `baldart update` manually.');
      } else if (cmpSemver(remoteVersion, version) > 0) {
        updateAvailable = true;
        UI.warning(`Update available: ${version} → ${remoteVersion}. Run: baldart update`);
      } else if (cmpSemver(remoteVersion, version) < 0) {
        UI.info(`Local v${version} is ahead of remote v${remoteVersion} (likely an unreleased commit).`);
      } else {
        UI.success(`Up to date (v${version})`);
      }
    } catch (error) {
      UI.warning('Cannot check for updates (offline?)');
    }

    // Summary
    UI.newline();
    let updateLine;
    if (updateAvailable && remoteVersion) {
      updateLine = `Update: ${version} → ${remoteVersion} available`;
    } else if (remoteVersion && remoteVersion !== 'unknown') {
      updateLine = `Update: up to date`;
    } else {
      updateLine = `Update: unknown (could not reach remote)`;
    }
    UI.box('SUMMARY', [
      `Version: ${version}`,
      `Installation: ${symlinkValid ? 'Valid' : 'Issues detected'}`,
      updateLine,
      '',
      'Commands available:',
      '  • baldart update  - Update framework',
      '  • baldart push    - Contribute changes',
      '  • baldart version - Show version'
    ]);

    UI.newline();

  } catch (error) {
    UI.error(`Status check failed: ${error.message}`);
    process.exit(1);
  }
}

module.exports = status;
