/**
 * Liste toutes les issues Gitea (ouvertes + fermées) pour jmartin/petitspas.
 * Token : .gitea-token (racine), GITEA_TOKEN, ou docs/27_BRIEFING-FRONTEND.md
 */
const https = require('https');
const fs = require('fs');
const path = require('path');

const repoRoot = path.join(__dirname, '../..');
let token = process.env.GITEA_TOKEN;
if (!token) {
  try {
    const tokenFile = path.join(repoRoot, '.gitea-token');
    if (fs.existsSync(tokenFile)) token = fs.readFileSync(tokenFile, 'utf8').trim();
  } catch (_) {}
}
if (!token) {
  try {
    const briefing = fs.readFileSync(
      path.join(repoRoot, 'docs/27_BRIEFING-FRONTEND.md'),
      'utf8',
    );
    const m = briefing.match(/Token:\s*(giteabu_[a-f0-9]+)/);
    if (m) token = m[1].trim();
  } catch (_) {}
}
if (!token) {
  console.error('Token non trouvé');
  process.exit(1);
}

function get(path) {
  return new Promise((resolve, reject) => {
    const opts = { hostname: 'git.ptits-pas.fr', path, method: 'GET', headers: { Authorization: 'token ' + token } };
    const req = https.request(opts, (res) => {
      let d = '';
      res.on('data', (c) => (d += c));
      res.on('end', () => {
        try { resolve(JSON.parse(d)); } catch (e) { reject(e); }
      });
    });
    req.on('error', reject);
    req.end();
  });
}

async function main() {
  const seen = new Map();
  for (const state of ['open', 'closed']) {
    for (let page = 1; ; page++) {
      const raw = await get('/api/v1/repos/jmartin/petitspas/issues?state=' + state + '&limit=50&page=' + page + '&type=issues');
      if (raw && raw.message && !Array.isArray(raw)) {
        console.error('API:', raw.message);
        process.exit(1);
      }
      const list = Array.isArray(raw) ? raw : [];
      for (const i of list) {
        if (!i.pull_request) seen.set(i.number, { number: i.number, title: i.title, state: i.state });
      }
      if (list.length < 50) break;
    }
  }
  const all = [...seen.values()].sort((a, b) => a.number - b.number);
  console.log(JSON.stringify(all, null, 2));
}

main().catch((e) => { console.error(e); process.exit(1); });
