const fs = require('fs');
const path = require('path');
const CliBridge = require('./cli-bridge');

const DATA_FILE = path.join(__dirname, '..', 'data', 'projects.json');

class ProjectManager {
  constructor() {
    this.projects = [];
    this._load();
    if (this.projects.length === 0) {
      this._autoRegister();
    }
  }

  _autoRegister() {
    // Scan parent directories up to 3 levels for ai-qa-workflow.js
    let dir = path.resolve(__dirname, '..', '..');
    for (let i = 0; i < 3; i++) {
      const parent = path.resolve(dir, '..');
      if (parent === dir) break;
      dir = parent;
    }
    // Check current and parent dirs
    const candidates = [
      path.resolve(__dirname, '..', '..'), // 2 levels up (project root from qa-dashboard/services/)
      path.resolve(__dirname, '..'),        // qa-dashboard/
      process.cwd(),                        // wherever node was called from
    ];
    for (const c of [...new Set(candidates)]) {
      if (c && fs.existsSync(path.join(c, 'ai-qa-workflow.js'))) {
        const name = path.basename(c);
        this.add(name, c);
        return;
      }
    }
  }

  _load() {
    if (fs.existsSync(DATA_FILE)) {
      try {
        this.projects = JSON.parse(fs.readFileSync(DATA_FILE, 'utf-8'));
      } catch { this.projects = []; }
    }
  }

  _save() {
    fs.writeFileSync(DATA_FILE, JSON.stringify(this.projects, null, 2), 'utf-8');
  }

  getAll() {
    return this.projects;
  }

  get(id) {
    return this.projects.find(p => p.id === id);
  }

  add(name, path) {
    const id = name.toLowerCase().replace(/[^a-z0-9]+/g, '-');
    const existing = this.projects.find(p => p.id === id);
    if (existing) {
      existing.name = name;
      existing.path = path;
      existing.updatedAt = new Date().toISOString();
      this._save();
      return existing;
    }
    const project = { id, name, path, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() };
    this.projects.push(project);
    this._save();
    return project;
  }

  remove(id) {
    this.projects = this.projects.filter(p => p.id !== id);
    this._save();
  }

  getBridge(id) {
    const project = this.get(id);
    if (!project) return null;
    return new CliBridge(project.path);
  }
}

module.exports = new ProjectManager();
