import express from 'express';
import fs from 'fs';
import path from 'path';
import os from 'os';

const router = express.Router();

function getWorkspacesRoot() {
  return os.homedir();
}

function expandWorkspacePath(inputPath) {
  if (!inputPath) return inputPath;
  if (inputPath === '~') return getWorkspacesRoot();
  if (inputPath.startsWith('~/') || inputPath.startsWith('~\\')) {
    return path.join(getWorkspacesRoot(), inputPath.slice(2));
  }
  return inputPath;
}

async function validateWorkspacePath(targetPath) {
  const resolved = path.resolve(targetPath);
  return { valid: true, resolvedPath: resolved };
}

router.get('/', async (req, res) => {
  try {
    const projectDir = process.env.CODEFREE_DIRECTORY || '';
    if (!projectDir) {
      return res.json([]);
    }

    const resolvedPath = path.resolve(projectDir);
    let stat;
    try {
      stat = await fs.promises.stat(resolvedPath);
    } catch (e) {
      return res.json([]);
    }

    if (!stat.isDirectory()) {
      return res.json([]);
    }

    const entries = await fs.promises.readdir(resolvedPath, { withFileTypes: true });
    const items = [];

    for (const entry of entries) {
      if (entry.name.startsWith('.')) continue;
      const fullPath = path.join(resolvedPath, entry.name);
      try {
        const entryStat = await fs.promises.stat(fullPath);
        items.push({
          name: entry.name,
          path: fullPath,
          lastModified: entryStat.mtime.toISOString(),
          type: entry.isDirectory() ? 'directory' : 'file',
          size: entry.isFile() ? entryStat.size : undefined,
        });
      } catch (e) {
        // skip inaccessible
      }
    }

    res.json({ rootPath: resolvedPath, items });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

router.get('/browse', async (req, res) => {
  try {
    const { path: dirPath } = req.query;
    const defaultRoot = getWorkspacesRoot();
    let targetPath = dirPath ? expandWorkspacePath(dirPath) : defaultRoot;
    targetPath = path.resolve(targetPath);

    const validation = await validateWorkspacePath(targetPath);
    if (!validation.valid) {
      return res.status(403).json({ error: validation.error });
    }

    const resolvedPath = validation.resolvedPath || targetPath;

    try {
      const stat = await fs.promises.stat(resolvedPath);
      if (!stat.isDirectory()) {
        return res.status(400).json({ error: 'Path is not a directory' });
      }
    } catch (err) {
      return res.status(404).json({ error: 'Directory not accessible' });
    }

    const entries = await fs.promises.readdir(resolvedPath, { withFileTypes: true });
    const directories = entries
      .filter((e) => e.isDirectory())
      .map((e) => ({ path: path.join(resolvedPath, e.name), name: e.name, type: 'directory' }))
      .sort((a, b) => a.name.localeCompare(b.name));

    res.json({ path: resolvedPath, suggestions: directories });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

router.post('/open', async (req, res) => {
  try {
    const { path: projectPath } = req.body;
    if (!projectPath) {
      return res.status(400).json({ error: 'Path is required' });
    }

    const expandedPath = expandWorkspacePath(projectPath);
    const resolvedPath = path.resolve(expandedPath);

    try {
      const stat = await fs.promises.stat(resolvedPath);
      if (!stat.isDirectory()) {
        return res.status(400).json({ error: 'Path is not a directory' });
      }
    } catch (err) {
      return res.status(404).json({ error: 'Directory not found' });
    }

    res.json({ success: true, path: resolvedPath, name: path.basename(resolvedPath) });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

export { router as projectsRouter };
