import { Pool } from 'pg';

const pool = new Pool({
  user: process.env.DB_USER || 'llm',
  password: process.env.DB_PASSWORD || 'llm_secure_2026',
  host: process.env.DB_HOST || '192.168.178.82', // Erik IPv4
  port: parseInt(process.env.DB_PORT || '5432'),
  database: process.env.DB_NAME || 'llm_gateway',
});

export interface BGPStatus {
  announced: boolean;
  origin_asns: number[];
  visibility_percent: number;
  last_seen: string;
}

export interface BGPRoute {
  prefix: string;
  origin_asn: number;
  visibility_percent: number;
  last_seen: string;
}

/**
 * Query local BGP database for prefix status
 * Returns announced status, origin ASNs, and visibility percentage
 */
export async function getBgpStatus(prefix: string): Promise<BGPStatus | null> {
  try {
    const result = await pool.query(
      `SELECT DISTINCT origin_asn, MAX(visibility_percent) as visibility_percent, MAX(last_seen) as last_seen
       FROM bgp_routes
       WHERE prefix = $1::cidr
       GROUP BY origin_asn`,
      [prefix]
    );

    if (result.rows.length === 0) {
      return {
        announced: false,
        origin_asns: [],
        visibility_percent: 0,
        last_seen: new Date().toISOString(),
      };
    }

    return {
      announced: true,
      origin_asns: result.rows.map(r => r.origin_asn),
      visibility_percent: Math.max(...result.rows.map(r => parseFloat(r.visibility_percent) || 0)),
      last_seen: result.rows[0].last_seen || new Date().toISOString(),
    };
  } catch (error) {
    console.error('[BGP Client] Error querying bgp_routes:', error);
    return null;
  }
}

/**
 * Query local BGP for all prefixes announced by an ASN
 */
export async function getAnnouncedPrefixes(asn: number): Promise<BGPRoute[]> {
  try {
    const result = await pool.query(
      `SELECT prefix, origin_asn, visibility_percent, last_seen
       FROM bgp_routes
       WHERE origin_asn = $1
       ORDER BY visibility_percent DESC`,
      [asn]
    );
    return result.rows;
  } catch (error) {
    console.error('[BGP Client] Error querying announced prefixes:', error);
    return [];
  }
}

/**
 * Check for potential BGP hijacks (multiple origin ASNs for same prefix)
 */
export async function checkBgpHijack(prefix: string): Promise<number[]> {
  try {
    const result = await pool.query(
      `SELECT DISTINCT origin_asn FROM bgp_routes WHERE prefix = $1::cidr`,
      [prefix]
    );
    return result.rows.length > 1 ? result.rows.map(r => r.origin_asn) : [];
  } catch (error) {
    console.error('[BGP Client] Error checking hijacks:', error);
    return [];
  }
}

/**
 * Get BGP statistics (total prefixes, ASNs, etc.)
 */
export async function getBgpStats() {
  try {
    const result = await pool.query(`
      SELECT
        COUNT(*) as total_prefixes,
        COUNT(DISTINCT origin_asn) as total_asns,
        MAX(last_seen) as last_import,
        MIN(visibility_percent) as min_visibility,
        AVG(visibility_percent) as avg_visibility,
        MAX(visibility_percent) as max_visibility
      FROM bgp_routes
    `);
    return result.rows[0] || null;
  } catch (error) {
    console.error('[BGP Client] Error querying stats:', error);
    return null;
  }
}

export async function cleanup() {
  await pool.end();
}
