import tweepy
import time
import csv
import os
import random

# ========== 認証情報をここに入力 ==========
API_KEY = 'f2546KJtO2ghVIDNOKKj2kYjx'
API_SECRET = 'ecKVMxCLzXr1eEXSQnsY3Jcze4MqlRycdgauzhYy7ZoPOpQVox'
ACCESS_TOKEN = '1322739132481728512-y73icn7XgptRHMyXUmrMqXB623kRLR'
ACCESS_SECRET = 'YkarHAtIT02bnkj329Pw5OFmEv7oDRvhuB656sxTguLDl'
BEARER_TOKEN = 'AAAAAAAAAAAAAAAAAAAAAE1Z2wEAAAAAhnml%2Fygwg45GWIyf8hPbEQLE0ek%3DFl8qVPMA2lcsBCogMGfp995HgvFX4xodQBZNfiKMh7tguLRmMv'

# ========== 対象設定 ==========

USERNAME = 'cardshop_gotcha'
TARGET_TWEET_ID = '1939539256466383347'
TARGET_CONVERSATION_ID = '1939539256466383347'
HASHTAG = '#カードショップGOTCHA2周年'
LOG_FILE = 'replies_log.csv'

# ========== クライアント設定 ==========

client = tweepy.Client(
    bearer_token=BEARER_TOKEN,
    consumer_key=API_KEY,
    consumer_secret=API_SECRET,
    access_token=ACCESS_TOKEN,
    access_token_secret=ACCESS_SECRET,
    wait_on_rate_limit=True
)

# ========== ログ読み込み ==========

def load_replied_user_ids(log_file):
    if not os.path.exists(log_file):
        return set()
    with open(log_file, newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        return set(row['author_id'] for row in reader)

# ========== ログ保存 ==========

def log_reply(log_file, author_id, tweet_id, reply_id, number):
    file_exists = os.path.exists(log_file)
    with open(log_file, mode='a', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=['number', 'author_id', 'original_tweet_id', 'reply_tweet_id'])
        if not file_exists:
            writer.writeheader()
        writer.writerow({
            'number': number,
            'author_id': author_id,
            'original_tweet_id': tweet_id,
            'reply_tweet_id': reply_id
        })

# ========== conversation_id でフィルタするリプライ取得 ==========

def get_filtered_replies(conversation_id):
    print(f"🔍 クエリ: conversation_id:{conversation_id}")
    replies = []

    paginator = tweepy.Paginator(
        client.search_recent_tweets,
        query=f"conversation_id:{conversation_id}",
        tweet_fields=['author_id', 'conversation_id', 'text'],
        max_results=100
    )

    for page in paginator:
        if not page.data:
            print("⚠️ データなしのページをスキップ")
            continue
        for tweet in page.data:
            print(f"👁️ チェック: {tweet.id} / conversation_id={tweet.conversation_id}")
            if str(tweet.conversation_id) == conversation_id:
                replies.append(tweet)
        time.sleep(1)
    return replies

# ========== メイン処理 ==========

def main():
    all_replies = get_filtered_replies(TARGET_CONVERSATION_ID)
    print(f"✅ 対象ツイートへの返信数：{len(all_replies)} 件")

    already_replied = load_replied_user_ids(LOG_FILE)
    print(f"📌 既に返信済みのユーザー数：{len(already_replied)}")

    target_replies = []
    for r in all_replies:
        if str(r.author_id) in already_replied:
            continue
        if HASHTAG not in r.text:
            continue
        target_replies.append(r)

    print(f"\n📊 対象リプライ件数（返信予定）：{len(target_replies)} 件\n")

    for i, tweet in enumerate(target_replies, start=1):
        author_id = tweet.author_id
        tweet_id = tweet.id
        reply_text = f"@{author_id} あなたは {HASHTAG} の参加者として {i}番目です！🎉"

        print(f"\n🚀 {i}件目の返信処理開始 → ユーザー: {author_id}")
        print(f"返信内容: {reply_text}")

        try:
            reply = client.create_tweet(
                in_reply_to_tweet_id=tweet_id,
                text=reply_text
            )
            print(f"✅ 投稿成功 → リプライID: {reply.data['id']}")
            log_reply(LOG_FILE, author_id, tweet_id, reply.data['id'], i)
            time.sleep(random.uniform(3.5, 6.0))
        except Exception as e:
            print(f"❌ エラー発生（{author_id}）: {e}")
            continue

    print("\n🎉 全処理が完了しました！")

# ========== 実行 ==========

if __name__ == "__main__":
    main()