import { promises as fs } from 'fs';
import path from 'path';
import { spawn } from 'child_process';
import { getUserPaths, getPublicPaths } from './user-directories.js';

const SYSTEM_MCP_REPO_URL = 'git@git.amberweather.com:mcp-server/hupoer-mcps.git';
const SYSTEM_MCP_REPO_OWNER = 'mcp-server';
const SYSTEM_MCP_REPO_NAME = 'hupoer-mcps';

function runGit(args, cwd) {
  return new Promise((resolve, reject) => {
    const gitProcess = spawn('git', args, {
      cwd,
      stdio: ['ignore', 'pipe', 'pipe'],
      env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }
    });
    let stderr = '';
    gitProcess.stderr.on('data', (data) => { stderr += data.toString(); });
    gitProcess.on('close', (code) => {
      if (code === 0) resolve();
      else reject(new Error(stderr || `Git ${args[0]} failed with code ${code}`));
    });
    gitProcess.on('error', (err) => { reject(err); });
  });
}

async function updateRepository(repoPath) {
  try {
    await runGit(['pull', '--ff-only'], repoPath);
  } catch (err) {
    if (err.message.includes('overwritten by merge') || err.message.includes('overwritten by checkout') || err.message.includes('local changes')) {
      console.log('[SystemMcpRepo] git pull failed due to local changes, discarding and retrying:', err.message);
      await runGit(['checkout', '--', '.'], repoPath);
      await runGit(['pull', '--ff-only'], repoPath);
    } else {
      throw err;
    }
  }
}

export async function ensureSystemMcpRepo() {
  const publicPaths = getPublicPaths();
  const publicRepoPath = path.join(publicPaths.mcpRepoDir, SYSTEM_MCP_REPO_OWNER, SYSTEM_MCP_REPO_NAME);

  try {
    await fs.access(publicRepoPath);
    // Already cloned — try to update
    try {
      await updateRepository(publicRepoPath);
    } catch (err) {
      console.log('[SystemMcpRepo] Failed to pull system MCP repo, using existing clone:', err.message);
    }
  } catch {
    // Not yet cloned
    await fs.mkdir(path.dirname(publicRepoPath), { recursive: true });
    try {
      await runGit(['clone', '--depth', '1', SYSTEM_MCP_REPO_URL, publicRepoPath], undefined);
      console.log('[SystemMcpRepo] Cloned system MCP repo to', publicRepoPath);
    } catch (err) {
      console.error('[SystemMcpRepo] Failed to clone system MCP repo:', err.message);
      throw err;
    }
  }

  return publicRepoPath;
}

/**
 * Initialize the built-in MCP repo for a user.
 * Idempotent: if the user already has the symlink, skip.
 */
export async function initSystemMcpRepoForUser(userUuid) {
  const userPaths = getUserPaths(userUuid);
  const userRepoPath = path.join(userPaths.mcpRepoDir, SYSTEM_MCP_REPO_OWNER, SYSTEM_MCP_REPO_NAME);

  try {
    await fs.lstat(userRepoPath);
    // Already set up — nothing to do
    return;
  } catch {
    // Doesn't exist — proceed with setup
  }

  let publicRepoPath;
  try {
    publicRepoPath = await ensureSystemMcpRepo();
  } catch (err) {
    console.error('[SystemMcpRepo] Could not ensure system MCP repo, skipping user init:', err.message);
    return;
  }

  await fs.mkdir(path.dirname(userRepoPath), { recursive: true });
  try {
    await fs.symlink(publicRepoPath, userRepoPath);
    console.log(`[SystemMcpRepo] Linked system MCP repo for user ${userUuid}`);
  } catch (err) {
    console.error(`[SystemMcpRepo] Failed to create symlink for user ${userUuid}:`, err.message);
  }
}

export { SYSTEM_MCP_REPO_OWNER, SYSTEM_MCP_REPO_NAME, SYSTEM_MCP_REPO_URL };
