/**
 * General operation tracker that works with any provider
 */

import type { Logger, MongoDBClient } from '@stock-bot/types';
import type { BaseOperationProvider } from './BaseOperationProvider';
import type {
  BulkOperationUpdate,
  OperationComponentOptions,
  OperationConfig,
  OperationStats,
  OperationUpdate,
  StaleSymbolOptions,
  SymbolWithOperations
} from './types';

/**
 * Tracks operation execution times and states for symbols
 */
export class OperationTracker {
  private mongodb: MongoDBClient;
  private logger: Logger;
  private provider: BaseOperationProvider;
  private indexesCreated: Set<string> = new Set();

  constructor(
    { mongodb, logger }: OperationComponentOptions,
    provider: BaseOperationProvider
  ) {
    this.mongodb = mongodb;
    this.logger = logger;
    this.provider = provider;
  }

  /**
   * Initialize the tracker and create indexes
   */
  async initialize(): Promise<void> {
    const { name } = this.provider.getProviderConfig();
    this.logger.info(`Initializing operation tracker for provider: ${name}`);

    // Initialize provider first
    await this.provider.initialize();

    // Create indexes for all operations
    const operations = this.provider.getOperations();
    for (const operation of operations) {
      await this.createOperationIndexes(operation);
    }

    this.logger.info(`Operation tracker initialized for ${name}`, {
      operationCount: operations.length
    });
  }

  /**
   * Create indexes for efficient operation queries
   */
  private async createOperationIndexes(operation: OperationConfig): Promise<void> {
    const { collectionName, symbolField } = this.provider.getProviderConfig();
    
    if (this.indexesCreated.has(operation.name)) {
      return;
    }

    try {
      const indexes = [
        // Index for finding stale symbols
        { 
          [`operations.${operation.name}.lastSuccessAt`]: 1, 
          [symbolField]: 1 
        },
        // Index for finding by last record date
        { 
          [`operations.${operation.name}.lastRecordDate`]: 1, 
          [symbolField]: 1 
        },
        // Index for operation status
        { 
          [`operations.${operation.name}.status`]: 1, 
          [symbolField]: 1 
        }
      ];

      // Add crawl state indexes for crawl operations
      if (operation.type === 'crawl' || operation.type === 'intraday_crawl') {
        indexes.push(
          { 
            [`operations.${operation.name}.crawlState.finished`]: 1, 
            [symbolField]: 1 
          },
          {
            [`operations.${operation.name}.crawlState.newestDateReached`]: 1,
            [symbolField]: 1
          },
          {
            [`operations.${operation.name}.crawlState.oldestDateReached`]: 1,
            [symbolField]: 1
          }
        );
      }

      const collection = this.mongodb.collection(collectionName);
      
      for (const indexSpec of indexes) {
        await collection.createIndex(indexSpec, {
          background: true,
          name: `op_${operation.name}_${Object.keys(indexSpec).join('_')}`
        });
      }

      this.indexesCreated.add(operation.name);
      
      this.logger.debug(`Created indexes for operation: ${operation.name}`, {
        provider: this.provider.getProviderConfig().name,
        operation: operation.name,
        indexCount: indexes.length
      });
    } catch (error) {
      this.logger.error(`Failed to create indexes for operation: ${operation.name}`, {
        error,
        provider: this.provider.getProviderConfig().name
      });
      throw error;
    }
  }

  /**
   * Update symbol operation status
   */
  async updateSymbolOperation(
    symbol: string,
    operationName: string,
    data: OperationUpdate
  ): Promise<void> {
    const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig();
    
    // Validate operation exists
    this.provider.validateOperation(operationName);

    // Call before hook
    await this.provider.beforeOperationUpdate(symbol, operationName, data);

    const update: any = {
      $set: {
        [`operations.${operationName}.lastRunAt`]: new Date(),
        [`operations.${operationName}.status`]: data.status,
        updated_at: new Date()
      }
    };

    // Only update lastSuccessAt on successful operations
    if (data.status === 'success') {
      update.$set[`operations.${operationName}.lastSuccessAt`] = new Date();
    }

    if (data.lastRecordDate) {
      update.$set[`operations.${operationName}.lastRecordDate`] = data.lastRecordDate;
    }

    if (data.recordCount !== undefined) {
      update.$set[`operations.${operationName}.recordCount`] = data.recordCount;
    }

    if (data.error) {
      update.$set[`operations.${operationName}.error`] = data.error;
    }

    if (data.metadata) {
      update.$set[`operations.${operationName}.metadata`] = data.metadata;
    }

    if (data.crawlState) {
      const existingPath = `operations.${operationName}.crawlState`;
      if (data.crawlState.finished !== undefined) {
        update.$set[`${existingPath}.finished`] = data.crawlState.finished;
      }
      if (data.crawlState.oldestDateReached) {
        update.$set[`${existingPath}.oldestDateReached`] = data.crawlState.oldestDateReached;
      }
      if (data.crawlState.newestDateReached) {
        update.$set[`${existingPath}.newestDateReached`] = data.crawlState.newestDateReached;
      }
      if (data.crawlState.lastProcessedDate) {
        update.$set[`${existingPath}.lastProcessedDate`] = data.crawlState.lastProcessedDate;
      }
      if (data.crawlState.totalDaysProcessed !== undefined) {
        update.$set[`${existingPath}.totalDaysProcessed`] = data.crawlState.totalDaysProcessed;
      }
      if (data.crawlState.lastCrawlDirection) {
        update.$set[`${existingPath}.lastCrawlDirection`] = data.crawlState.lastCrawlDirection;
      }
      if (data.crawlState.targetOldestDate) {
        update.$set[`${existingPath}.targetOldestDate`] = data.crawlState.targetOldestDate;
      }
      if (data.crawlState.metadata) {
        update.$set[`${existingPath}.metadata`] = data.crawlState.metadata;
      }
    }

    await this.mongodb.updateOne(
      collectionName,
      { [symbolField]: symbol },
      update
    );

    // Call after hook
    await this.provider.afterOperationUpdate(symbol, operationName, data);

    this.logger.debug('Updated symbol operation', {
      provider: providerName,
      symbol,
      operation: operationName,
      status: data.status
    });
  }

  /**
   * Bulk update symbol operations for performance
   */
  async bulkUpdateSymbolOperations(updates: BulkOperationUpdate[]): Promise<void> {
    if (updates.length === 0) {return;}

    const { collectionName, symbolField, name: providerName } = this.provider.getProviderConfig();

    // Group by operation for validation
    const operationGroups = new Map<string, BulkOperationUpdate[]>();
    for (const update of updates) {
      this.provider.validateOperation(update.operation);
      
      const group = operationGroups.get(update.operation) || [];
      group.push(update);
      operationGroups.set(update.operation, group);
    }

    // Call before hooks
    for (const update of updates) {
      await this.provider.beforeOperationUpdate(update.symbol, update.operation, update.data);
    }

    // Build bulk operations
    const bulkOps = updates.map(({ symbol, operation, data }) => {
      const update: any = {
        $set: {
          [`operations.${operation}.lastRunAt`]: new Date(),
          [`operations.${operation}.status`]: data.status,
          updated_at: new Date()
        }
      };

      if (data.status === 'success') {
        update.$set[`operations.${operation}.lastSuccessAt`] = new Date();
      }

      if (data.lastRecordDate) {
        update.$set[`operations.${operation}.lastRecordDate`] = data.lastRecordDate;
      }

      if (data.recordCount !== undefined) {
        update.$set[`operations.${operation}.recordCount`] = data.recordCount;
      }

      if (data.error) {
        update.$set[`operations.${operation}.error`] = data.error;
      }

      if (data.metadata) {
        update.$set[`operations.${operation}.metadata`] = data.metadata;
      }

      if (data.crawlState) {
        const basePath = `operations.${operation}.crawlState`;
        Object.entries(data.crawlState).forEach(([key, value]) => {
          if (value !== undefined) {
            // Handle Date objects properly
            if (value instanceof Date || (typeof value === 'string' && key.includes('Date'))) {
              update.$set[`${basePath}.${key}`] = new Date(value);
            } else {
              update.$set[`${basePath}.${key}`] = value;
            }
          }
        });
      }

      return {
        updateOne: {
          filter: { [symbolField]: symbol },
          update
        }
      };
    });

    const collection = this.mongodb.collection(collectionName);
    const result = await collection.bulkWrite(bulkOps, { ordered: false });

    // Call after hooks
    for (const update of updates) {
      await this.provider.afterOperationUpdate(update.symbol, update.operation, update.data);
    }

    this.logger.debug('Bulk updated symbol operations', {
      provider: providerName,
      totalUpdates: updates.length,
      modified: result.modifiedCount,
      operations: Array.from(operationGroups.keys())
    });
  }

  /**
   * Get symbols that need processing for an operation
   */
  async getStaleSymbols(
    operationName: string,
    options: StaleSymbolOptions = {}
  ): Promise<string[]> {
    const { collectionName, symbolField } = this.provider.getProviderConfig();
    const { 
      limit = 1000, 
      excludeSymbols = [], 
      activeOnly = true,
      symbolFilter
    } = options;

    this.provider.validateOperation(operationName);

    const cutoffDate = options.notRunSince || (() => {
      const date = new Date();
      const hours = options.minHoursSinceRun || this.provider.getDefaultStaleHours(operationName);
      date.setHours(date.getHours() - hours);
      return date;
    })();

    const filter: any = {
      $or: [
        { [`operations.${operationName}.lastSuccessAt`]: { $lt: cutoffDate } },
        { [`operations.${operationName}.lastSuccessAt`]: { $exists: false } },
        { [`operations.${operationName}`]: { $exists: false } }
      ]
    };

    if (activeOnly) {
      filter.active = { $ne: false };
    }

    if (excludeSymbols.length > 0) {
      filter[symbolField] = { $nin: excludeSymbols };
    }

    // Add symbol filter if provided
    if (symbolFilter?.symbol) {
      filter.symbol = symbolFilter.symbol;
    }

    const symbols = await this.mongodb.find(collectionName, filter, {
      limit,
      projection: { [symbolField]: 1 },
      sort: { [`operations.${operationName}.lastSuccessAt`]: 1 }
    });

    return symbols.map(doc => doc[symbolField]);
  }

  /**
   * Get symbols for crawl operations
   */
  async getSymbolsForCrawl(
    operationName: string,
    options: {
      limit?: number;
      includeFinished?: boolean;
    } = {}
  ): Promise<SymbolWithOperations[]> {
    const { collectionName, symbolField } = this.provider.getProviderConfig();
    const { limit = 100, includeFinished = false } = options;

    this.provider.validateOperation(operationName);

    const filter: any = {
      active: { $ne: false }
    };

    if (!includeFinished) {
      filter[`operations.${operationName}.crawlState.finished`] = { $ne: true };
    }

    const symbols = await this.mongodb.find(collectionName, filter, {
      limit,
      projection: {
        [symbolField]: 1,
        [`operations.${operationName}`]: 1
      },
      sort: {
        [`operations.${operationName}.lastRunAt`]: 1
      }
    });

    return symbols.map(doc => ({
      symbol: doc[symbolField],
      lastRecordDate: doc.operations?.[operationName]?.lastRecordDate,
      operationStatus: doc.operations?.[operationName]
    }));
  }

  /**
   * Mark crawl as finished
   */
  async markCrawlFinished(
    symbol: string,
    operationName: string,
    oldestDateReached: Date,
    newestDateReached?: Date
  ): Promise<void> {
    await this.updateSymbolOperation(symbol, operationName, {
      status: 'success',
      crawlState: {
        finished: true,
        oldestDateReached,
        newestDateReached: newestDateReached || new Date()
      }
    });

    this.logger.info('Marked crawl as finished', {
      provider: this.provider.getProviderConfig().name,
      symbol,
      operation: operationName,
      oldestDateReached,
      newestDateReached
    });
  }

  /**
   * Get symbols for intraday crawl with gap detection
   */
  async getSymbolsForIntradayCrawl(
    operationName: string,
    options: {
      limit?: number;
      targetOldestDate?: Date;
      includeNewDataGaps?: boolean;
      symbolFilter?: { symbol?: string };
    } = {}
  ): Promise<Array<SymbolWithOperations & { gaps?: { forward?: boolean; backward?: boolean } }>> {
    const { collectionName, symbolField } = this.provider.getProviderConfig();
    const { limit = 100, targetOldestDate, includeNewDataGaps = true, symbolFilter } = options;

    this.provider.validateOperation(operationName);

    // Build filter
    const filter: any = {
      active: { $ne: false }
    };

    // Add symbol filter if provided
    if (symbolFilter?.symbol) {
      filter.symbol = symbolFilter.symbol;
    }

    // Get all symbols that either:
    // 1. Have never been crawled
    // 2. Are not finished
    // 3. Have gaps (new data since last crawl)
    const orConditions = [
      { [`operations.${operationName}`]: { $exists: false } },
      { [`operations.${operationName}.crawlState.finished`]: { $ne: true } }
    ];

    if (includeNewDataGaps) {
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      yesterday.setHours(0, 0, 0, 0);
      
      orConditions.push({
        [`operations.${operationName}.crawlState.newestDateReached`]: { $lt: yesterday }
      });
    }

    filter.$or = orConditions;

    const symbols = await this.mongodb.find(collectionName, filter, {
      limit,
      projection: {
        [symbolField]: 1,
        [`operations.${operationName}`]: 1,
        // Include common fields that might be needed
        symbol: 1,
        exchange: 1,
        qmSearchCode: 1
      },
      sort: {
        [`operations.${operationName}.lastRunAt`]: 1
      }
    });

    return symbols.map(doc => {
      const opStatus = doc.operations?.[operationName];
      const crawlState = opStatus?.crawlState;
      
      // Determine gaps (only backward since we removed forward crawling)
      const gaps: { forward?: boolean; backward?: boolean } = {};
      
      if (crawlState) {
        // Only check for backward gap (historical data)
        if (!crawlState.finished) {
          gaps.backward = true;
          if (targetOldestDate && crawlState.oldestDateReached) {
            gaps.backward = new Date(crawlState.oldestDateReached) > targetOldestDate;
          }
        }
      } else {
        // Never crawled, needs backward crawl
        gaps.backward = true;
      }

      return {
        symbol: doc[symbolField],
        lastRecordDate: opStatus?.lastRecordDate,
        operationStatus: opStatus,
        gaps,
        // Include other potentially useful fields
        exchange: doc.exchange,
        qmSearchCode: doc.qmSearchCode || doc[symbolField]
      } as SymbolWithOperations & { gaps?: { forward?: boolean; backward?: boolean } };
    });
  }

  /**
   * Check if intraday crawl is complete
   */
  async isIntradayCrawlComplete(
    symbol: string,
    operationName: string,
    targetOldestDate: Date
  ): Promise<boolean> {
    const { collectionName, symbolField } = this.provider.getProviderConfig();
    
    const doc = await this.mongodb.findOne(collectionName, {
      [symbolField]: symbol
    }, {
      projection: { [`operations.${operationName}.crawlState`]: 1 }
    });

    if (!doc?.operations?.[operationName]?.crawlState) {
      return false;
    }

    const crawlState = doc.operations[operationName].crawlState;
    
    // Check if explicitly marked as finished
    if (crawlState.finished) {
      return true;
    }

    // Check if we've reached the target oldest date
    if (crawlState.oldestDateReached && targetOldestDate) {
      return new Date(crawlState.oldestDateReached) <= targetOldestDate;
    }

    return false;
  }

  /**
   * Get symbols that need data updates based on last record date
   */
  async getSymbolsNeedingUpdate(
    operationName: string,
    options: {
      lastRecordBefore?: Date;
      neverRun?: boolean;
      limit?: number;
    } = {}
  ): Promise<SymbolWithOperations[]> {
    const { collectionName, symbolField } = this.provider.getProviderConfig();
    const { limit = 500 } = options;

    this.provider.validateOperation(operationName);

    const filter: any = {
      active: { $ne: false }
    };

    if (options.neverRun) {
      filter[`operations.${operationName}`] = { $exists: false };
    } else if (options.lastRecordBefore) {
      filter.$or = [
        { [`operations.${operationName}.lastRecordDate`]: { $lt: options.lastRecordBefore } },
        { [`operations.${operationName}`]: { $exists: false } }
      ];
    }

    const symbols = await this.mongodb.find(collectionName, filter, {
      limit,
      projection: {
        [symbolField]: 1,
        [`operations.${operationName}.lastRecordDate`]: 1,
        [`operations.${operationName}`]: 1
      },
      sort: { [`operations.${operationName}.lastRecordDate`]: 1 }
    });

    return symbols.map(doc => ({
      symbol: doc[symbolField],
      lastRecordDate: doc.operations?.[operationName]?.lastRecordDate,
      operationStatus: doc.operations?.[operationName]
    }));
  }

  /**
   * Get operation statistics
   */
  async getOperationStats(operationName: string): Promise<OperationStats> {
    const { collectionName } = this.provider.getProviderConfig();
    const operation = this.provider.getOperation(operationName);
    
    if (!operation) {
      throw new Error(`Unknown operation: ${operationName}`);
    }

    const collection = this.mongodb.collection(collectionName);
    
    const [
      total,
      processed,
      successful,
      failed,
      staleStats,
      crawlStats,
      recordStats
    ] = await Promise.all([
      // Total symbols
      collection.countDocuments({}),
      
      // Processed symbols
      collection.countDocuments({
        [`operations.${operationName}`]: { $exists: true }
      }),
      
      // Successful symbols
      collection.countDocuments({
        [`operations.${operationName}.status`]: 'success'
      }),
      
      // Failed symbols
      collection.countDocuments({
        [`operations.${operationName}.status`]: 'failure'
      }),
      
      // Stale symbols
      this.countStaleSymbols(operationName, operation.defaultStaleHours || 24),
      
      // Crawl stats (if applicable)
      (operation.type === 'crawl' || operation.type === 'intraday_crawl')
        ? collection.countDocuments({
            [`operations.${operationName}.crawlState.finished`]: true
          })
        : Promise.resolve(undefined),
      
      // Average records
      this.calculateAverageRecords(operationName)
    ]);

    const result: OperationStats = {
      totalSymbols: total,
      processedSymbols: processed,
      staleSymbols: staleStats,
      successfulSymbols: successful,
      failedSymbols: failed
    };

    if (crawlStats !== undefined) {
      result.finishedCrawls = crawlStats;
    }

    if (recordStats !== undefined) {
      result.avgRecordsPerSymbol = recordStats;
    }

    return result;
  }

  /**
   * Count stale symbols
   */
  private async countStaleSymbols(operationName: string, staleHours: number): Promise<number> {
    const { collectionName } = this.provider.getProviderConfig();
    const collection = this.mongodb.collection(collectionName);
    
    const staleDate = new Date();
    staleDate.setHours(staleDate.getHours() - staleHours);

    return collection.countDocuments({
      $or: [
        { [`operations.${operationName}.lastSuccessAt`]: { $lt: staleDate } },
        { [`operations.${operationName}`]: { $exists: false } }
      ]
    });
  }

  /**
   * Calculate average records per symbol
   */
  private async calculateAverageRecords(operationName: string): Promise<number | undefined> {
    const { collectionName } = this.provider.getProviderConfig();
    const collection = this.mongodb.collection(collectionName);
    
    const aggregation = await collection.aggregate([
      {
        $match: {
          [`operations.${operationName}.recordCount`]: { $exists: true }
        }
      },
      {
        $group: {
          _id: null,
          avgRecords: { $avg: `$operations.${operationName}.recordCount` }
        }
      }
    ]).toArray();

    if (aggregation.length > 0 && aggregation[0].avgRecords) {
      return Math.round(aggregation[0].avgRecords);
    }

    return undefined;
  }

  /**
   * Get provider info
   */
  getProviderInfo() {
    return this.provider.getProviderConfig();
  }
}