#!/usr/bin/env node
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const os = require('os');

const packageJson = require('../package.json');
const ACTIVATION_FILE = path.join(os.homedir(), '.reepoe', 'activation.json');

// ============= FLAG HANDLING FIRST =============
const args = process.argv.slice(2);

// Handle --version / -v
if (args.includes('--version') || args.includes('-v')) {
  console.log(packageJson.version);
  process.exit(0);
}

// Handle --help / -h
if (args.includes('--help') || args.includes('-h') || args.length === 0) {
  console.log(`
ReePoe v${packageJson.version} - AI Context Optimization Layer

USAGE:
  reepoe [options]
  reepoe <query>
  reepoe query <query>

OPTIONS:
  --version, -v    Show version number
  --help, -h       Show this help message

COMMANDS:
  reepoe-start     Start the ReePoe server (run this first!)
  reepoe-stop      Stop the ReePoe server
  reepoe-status    Check server status
  reepoe-metrics   Show usage metrics

EXAMPLES:
  reepoe "where is authentication handled?"
  reepoe query "find all API endpoints"

For more info: https://reepoe.com
`);
  process.exit(0);
}

// ============= QUERY HANDLING =============

function loadActivation() {
  if (!fs.existsSync(ACTIVATION_FILE)) {
    console.error('❌ Not activated. Run: reepoe-start');
    process.exit(1);
  }
  return JSON.parse(fs.readFileSync(ACTIVATION_FILE, 'utf8'));
}

async function query(instruction) {
  const activation = loadActivation();
  const API_BASE = activation.api_base || 'http://localhost:8000';
  
  console.log(`🤖 ReePoe processing: "${instruction}"`);
  
  try {
    const response = await axios.post(`${API_BASE}/query`, {
      instruction,
      user_email: activation.email
    }, { timeout: 60000 });
    
    console.log(JSON.stringify(response.data, null, 2));
  } catch (error) {
    console.error('❌ Query failed:', error.response?.data?.detail || error.message);
    process.exit(1);
  }
}

// Support both "reepoe query <text>" AND "reepoe <text>"
let queryText;
if (args[0] === 'query') {
  queryText = args.slice(1).join(' ');
} else {
  queryText = args.join(' ');
}

if (!queryText) {
  console.log('Usage: reepoe query "your question" OR reepoe "your question"');
  console.log('Run reepoe --help for more options');
  process.exit(1);
}

query(queryText);
