import {
  searchRecentTweets,
  likeTweet,
} from './twitter-api.service';
import {
  insertEngagement,
  hasEngagedWith,
} from '../twitter-data-queries';
import {
  getUpcomingGames,
  getActiveLeagues,
} from '../../seo/data-queries';

const ENGAGEMENT_ENABLED = process.env.TWITTER_ENGAGEMENT_ENABLED === 'true';
const MAX_LIKES_PER_CYCLE = 5;

function getETDate(): Date {
  const etDateStr = new Date().toLocaleDateString('en-CA', { timeZone: 'America/New_York' });
  return new Date(etDateStr + 'T12:00:00');
}

// ── Search + Like + Reply ────────────────────────────────────

export async function runEngagementCycle(): Promise<number> {
  if (!ENGAGEMENT_ENABLED) {
    console.log('[engagement] Engagement disabled — skipping');
    return 0;
  }

  let actionsCount = 0;
  const leagues = await getActiveLeagues();

  for (const league of leagues.slice(0, 3)) {
    try {
      // Build search queries from today's games
      const today = getETDate();
      const games = await getUpcomingGames(league, today);
      if (games.length === 0) continue;

      const searchTerms = games.slice(0, 3).map(g => `${g.awayTeam} ${g.homeTeam}`);
      const query = `(${searchTerms.join(' OR ')}) (bet OR pick OR spread OR over OR under) -is:retweet lang:en`;

      const tweets = await searchRecentTweets(query, 25);
      console.log(`[engagement] ${league}: search returned ${tweets.length} tweets`);
      if (!tweets.length) continue;

      // Filter: 15min-8hr old, low engagement bar for volume
      const now = Date.now();
      const filtered = tweets.filter(t => {
        const age = now - new Date(t.created_at).getTime();
        const ageHours = age / (1000 * 60 * 60);
        if (ageHours < 0.25 || ageHours > 8) return false;
        if (t.public_metrics.like_count < 1 && t.public_metrics.retweet_count < 1) return false;
        return true;
      });
      console.log(`[engagement] ${league}: ${filtered.length} tweets passed filter (of ${tweets.length})`);

      // Sort by engagement
      filtered.sort((a, b) =>
        (b.public_metrics.like_count + b.public_metrics.retweet_count * 3) -
        (a.public_metrics.like_count + a.public_metrics.retweet_count * 3)
      );

      // Like top tweets
      let likesThisCycle = 0;
      for (const tweet of filtered) {
        if (likesThisCycle >= MAX_LIKES_PER_CYCLE) break;
        if (await hasEngagedWith(tweet.id, 'like')) continue;

        try {
          await likeTweet(tweet.id);
          await insertEngagement({
            actionType: 'like',
            targetTweetId: tweet.id,
            targetUser: tweet.author_id,
          });
          likesThisCycle++;
          actionsCount++;
          await new Promise(r => setTimeout(r, 2000)); // rate limit courtesy
        } catch (err) {
          console.error(`[engagement] Like failed for ${tweet.id}:`, (err as Error).message);
        }
      }

      // Replies disabled — Twitter free-tier API returns 403 for replies
      // to tweets we haven't been mentioned in and for posts with @mentions.
    } catch (err) {
      console.error(`[engagement] Engagement cycle error for ${league}:`, (err as Error).message);
    }
  }

  console.log(`[engagement] Cycle completed — ${actionsCount} actions`);
  return actionsCount;
}

// ── Mention Processing (Disabled) ────────────────────────────

export async function processMentions(): Promise<number> {
  // Disabled — Twitter free-tier API returns 403 for replies and @mentions.
  // Likes-only engagement still works via runEngagementCycle().
  return 0;
}
