/**
 * Project routes — /api/project, /api/profile, /api/metadata
 */
import fs from 'fs';
import path from 'path';
import { normalizeProjectMeta } from '../../vl/metadata-extractor.js';
import { APP_VERSION } from '../../utils/config.js';
import { ensureProjectProfile } from '../helpers.js';

export function setupProjectRoutes(app, server) {
  // --- Project info ---
  app.get('/api/project', (req, res) => {
    const hasWorkspace = server.hasSelectedWorkspace();
    res.json({
      summary: hasWorkspace ? server.projectContext.getSummary() : server._buildEmptySummary(),
      isVL: hasWorkspace ? server.projectContext.isVLProject() : false,
      workDir: server.getVisibleWorkDir(),
      model: server.config.model,
      version: APP_VERSION,
      port: server._serverPort || server.config.port,
    });
  });

  // --- Profile (.vl-code/project.json) ---
  app.get('/api/profile', (req, res) => {
    try {
      if (!server.hasSelectedWorkspace()) return res.json({});
      const profilePath = path.join(server.config.workDir, '.vl-code', 'project.json');
      if (fs.existsSync(profilePath)) {
        const profile = JSON.parse(fs.readFileSync(profilePath, 'utf-8'));
        res.json(profile);
      } else {
        res.json({});
      }
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  });

  app.post('/api/profile', (req, res) => {
    try {
      if (!server.hasSelectedWorkspace()) {
        return res.status(400).json({ error: 'No workspace selected' });
      }
      const profilePath = path.join(server.config.workDir, '.vl-code', 'project.json');
      const dir = path.dirname(profilePath);
      if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
      let profile = {};
      if (fs.existsSync(profilePath)) profile = JSON.parse(fs.readFileSync(profilePath, 'utf-8'));
      Object.assign(profile, req.body);
      fs.writeFileSync(profilePath, JSON.stringify(profile, null, 2));
      res.json({ ok: true });
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  });

  // --- Metadata (ProjectMeta.json) ---
  app.get('/api/metadata', (req, res) => {
    if (!server.hasSelectedWorkspace()) return res.json({ meta: null, error: 'No workspace selected' });
    const meta = server.projectContext.getProjectMeta?.() || server.projectContext.projectMeta;
    if (meta) res.json({ meta });
    else res.json({ meta: null, error: 'No ProjectMeta found' });
  });

  app.post('/api/metadata', (req, res) => {
    try {
      if (!server.hasSelectedWorkspace()) {
        return res.status(400).json({ error: 'No workspace selected' });
      }
      const metaPath = path.join(server.config.workDir, '.vl-code', 'ProjectMeta.json');
      const dir = path.dirname(metaPath);
      if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
      const normalized = normalizeProjectMeta(req.body);
      fs.writeFileSync(metaPath, JSON.stringify(normalized, null, 2));
      server.projectContext.projectMeta = normalized;
      res.json({ ok: true });
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  });

  app.get('/api/metadata/extract', async (req, res) => {
    try {
      if (!server.hasSelectedWorkspace()) return res.json({ meta: null, error: 'No workspace selected' });
      await server.projectContext.scan();
      const { extractFromFileTree } = await import('../../vl/metadata-extractor.js');
      const files = server.projectContext.getAllFiles();
      const fileTree = {};
      for (const f of files) {
        try {
          fileTree[f.path] = fs.readFileSync(f.fullPath, 'utf-8');
        } catch {}
      }
      const meta = extractFromFileTree(fileTree, server.config.workDir);
      if (meta) {
        const metaPath = path.join(server.config.workDir, '.vl-code', 'ProjectMeta.json');
        const dir = path.dirname(metaPath);
        if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
        fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2));
        server.projectContext.projectMeta = meta;
        res.json({ meta });
      } else {
        res.json({ meta: null, error: 'Could not extract metadata' });
      }
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  });

  // --- Project init (one-click scaffolding) ---
  app.post('/api/project/init', async (req, res) => {
    try {
      if (!server.hasSelectedWorkspace()) {
        return res.status(400).json({ error: 'No workspace selected' });
      }
      const { projectName, template } = req.body;
      const dirs = ['Apps', 'Sections', 'ExtComponents', 'Services', 'Database', 'Theme'];
      for (const d of dirs) {
        const dirPath = path.join(server.config.workDir, d);
        if (!fs.existsSync(dirPath)) fs.mkdirSync(dirPath, { recursive: true });
      }
      ensureProjectProfile(server.config.workDir, null);
      await server.projectContext.load();
      server.broadcast({ type: 'file_tree_updated' });
      res.json({ ok: true, projectName: projectName || path.basename(server.config.workDir) });
    } catch (e) {
      res.status(500).json({ error: e.message });
    }
  });
}
