#!/usr/bin/env python3
"""Search tweets or get user tweets"""
import json
import sys
import requests
from requests_oauthlib import OAuth1

def get_auth():
    with open('/home/clawd/secrets/twitter/credentials.json') as f:
        creds = json.load(f)
    oauth1 = creds['oauth1']
    return OAuth1(
        oauth1['consumer_key'],
        oauth1['consumer_secret'],
        oauth1['access_token'],
        oauth1['access_token_secret']
    )

def search_tweets(query: str, max_results: int = 10) -> dict:
    """Search recent tweets"""
    auth = get_auth()
    url = "https://api.twitter.com/2/tweets/search/recent"
    params = {
        "query": query,
        "max_results": max_results,
        "tweet.fields": "author_id,conversation_id,created_at,in_reply_to_user_id",
        "expansions": "author_id",
        "user.fields": "username"
    }
    response = requests.get(url, auth=auth, params=params)
    return {"status": response.status_code, "response": response.json()}

def get_user_tweets(username: str, max_results: int = 10) -> dict:
    """Get recent tweets from a user"""
    auth = get_auth()
    # First get user ID
    user_url = f"https://api.twitter.com/2/users/by/username/{username}"
    user_resp = requests.get(user_url, auth=auth)
    if user_resp.status_code != 200:
        return {"status": user_resp.status_code, "response": user_resp.json()}
    
    user_id = user_resp.json()['data']['id']
    
    # Get tweets
    tweets_url = f"https://api.twitter.com/2/users/{user_id}/tweets"
    params = {
        "max_results": max_results,
        "tweet.fields": "conversation_id,created_at,in_reply_to_user_id"
    }
    response = requests.get(tweets_url, auth=auth, params=params)
    return {"status": response.status_code, "response": response.json()}

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: twitter_search.py search <query> | user <username>")
        sys.exit(1)
    
    cmd = sys.argv[1]
    if cmd == "search" and len(sys.argv) >= 3:
        result = search_tweets(sys.argv[2])
    elif cmd == "user" and len(sys.argv) >= 3:
        result = get_user_tweets(sys.argv[2])
    else:
        print("Usage: twitter_search.py search <query> | user <username>")
        sys.exit(1)
    
    print(json.dumps(result, indent=2))
