import dotenv from 'dotenv';
import { Pool } from 'pg';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

dotenv.config({ path: join(__dirname, '..', '.env') });

const dbConfig = {
  host: process.env.LOCAL_DB_HOST || '192.168.8.151',
  port: parseInt(process.env.LOCAL_DB_PORT || '5432'),
  user: process.env.LOCAL_DB_USER || 'postgres',
  password: process.env.LOCAL_DB_PASSWORD || 'postgres',
  database: process.env.LOCAL_DB_NAME || 'institutional_trader'
};

async function checkDatabaseDates() {
  const pool = new Pool(dbConfig);
  
  try {
    console.log('📊 Checking available dates in OptionsFlow_monthly...\n');
    
    // Check date range
    const dateRangeQuery = `
      SELECT 
        MIN(
          CASE 
            WHEN "CreatedDate"::text ~ '^\\d{4}-\\d{2}-\\d{2}$' 
              THEN "CreatedDate"::date
            WHEN "CreatedDate"::text ~ '^\\d{1,2}/\\d{1,2}/\\d{2,4}$'
              THEN to_date("CreatedDate"::text, 'MM/DD/YYYY')
            ELSE NULL
          END
        ) as min_date,
        MAX(
          CASE 
            WHEN "CreatedDate"::text ~ '^\\d{4}-\\d{2}-\\d{2}$' 
              THEN "CreatedDate"::date
            WHEN "CreatedDate"::text ~ '^\\d{1,2}/\\d{1,2}/\\d{2,4}$'
              THEN to_date("CreatedDate"::text, 'MM/DD/YYYY')
            ELSE NULL
          END
        ) as max_date,
        COUNT(*) as total_rows
      FROM "OptionsFlow_monthly"
    `;
    
    const dateRange = await pool.query(dateRangeQuery);
    console.log('Date Range:');
    console.table(dateRange.rows[0]);
    
    // Get dates with most recent data
    const recentDatesQuery = `
      SELECT 
        CASE 
          WHEN "CreatedDate"::text ~ '^\\d{4}-\\d{2}-\\d{2}$' 
            THEN "CreatedDate"::date
          WHEN "CreatedDate"::text ~ '^\\d{1,2}/\\d{1,2}/\\d{2,4}$'
            THEN to_date("CreatedDate"::text, 'MM/DD/YYYY')
          ELSE NULL
        END as date_val,
        COUNT(*) as row_count
      FROM "OptionsFlow_monthly"
      WHERE "Premium" IS NOT NULL
        AND btrim("Premium"::text) <> ''
        AND "StockEtf" = 'STOCK'
      GROUP BY date_val
      ORDER BY date_val DESC
      LIMIT 20
    `;
    
    const recentDates = await pool.query(recentDatesQuery);
    console.log('\n📅 Most Recent Dates with Data:');
    console.table(recentDates.rows);
    
    // Check for today's date specifically
    const today = new Date().toISOString().split('T')[0];
    const todayQuery = `
      SELECT COUNT(*) as count
      FROM "OptionsFlow_monthly"
      WHERE (
        CASE 
          WHEN "CreatedDate"::text ~ '^\\d{4}-\\d{2}-\\d{2}$' 
            THEN "CreatedDate"::date
          WHEN "CreatedDate"::text ~ '^\\d{1,2}/\\d{1,2}/\\d{2,4}$'
            THEN to_date("CreatedDate"::text, 'MM/DD/YYYY')
          ELSE NULL
        END
      ) = $1::date
    `;
    
    const todayResult = await pool.query(todayQuery, [today]);
    console.log(`\n📅 Data for today (${today}): ${todayResult.rows[0].count} rows`);
    
  } catch (error) {
    console.error('Error:', error.message);
  } finally {
    await pool.end();
  }
}

checkDatabaseDates();

