/**
 * Step: telegram-auth — Verify Telegram bot token configuration.
 */
import fs from 'fs';
import path from 'path';

import { logger } from '../src/logger.js';
import { emitStatus } from './status.js';

function parseEnv(content: string): Record<string, string> {
  const result: Record<string, string> = {};
  for (const line of content.split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const idx = trimmed.indexOf('=');
    if (idx === -1) continue;
    const key = trimmed.slice(0, idx).trim();
    const rawValue = trimmed.slice(idx + 1).trim();
    result[key] = rawValue.replace(/^['"]|['"]$/g, '');
  }
  return result;
}

async function verifyTelegramToken(token: string): Promise<{
  ok: boolean;
  username?: string;
  error?: string;
}> {
  try {
    const response = await fetch(`https://api.telegram.org/bot${token}/getMe`);
    const body = (await response.json()) as {
      ok?: boolean;
      description?: string;
      result?: { username?: string };
    };

    if (!response.ok || !body.ok) {
      return {
        ok: false,
        error: body.description || `telegram_http_${response.status}`,
      };
    }

    return {
      ok: true,
      username: body.result?.username,
    };
  } catch (err) {
    return {
      ok: false,
      error: err instanceof Error ? err.message : String(err),
    };
  }
}

export async function run(_args: string[]): Promise<void> {
  const projectRoot = process.cwd();
  const envFile = path.join(projectRoot, '.env');

  if (!fs.existsSync(envFile)) {
    emitStatus('AUTH_TELEGRAM', {
      STATUS: 'failed',
      ERROR: 'env_missing',
      LOG: 'logs/setup.log',
    });
    process.exit(4);
  }

  const env = parseEnv(fs.readFileSync(envFile, 'utf-8'));
  const token = env.TELEGRAM_BOT_TOKEN;

  if (!token) {
    emitStatus('AUTH_TELEGRAM', {
      STATUS: 'failed',
      ERROR: 'missing_telegram_bot_token',
      LOG: 'logs/setup.log',
    });
    process.exit(4);
  }

  logger.info('Verifying Telegram bot token');
  const result = await verifyTelegramToken(token);

  if (!result.ok) {
    emitStatus('AUTH_TELEGRAM', {
      STATUS: 'failed',
      AUTH_STATUS: 'invalid',
      ERROR: result.error || 'telegram_verification_failed',
      LOG: 'logs/setup.log',
    });
    process.exit(1);
  }

  emitStatus('AUTH_TELEGRAM', {
    STATUS: 'success',
    AUTH_STATUS: 'verified',
    BOT_USERNAME: result.username || '',
    LOG: 'logs/setup.log',
  });
}
