import logging
import sys
import argparse
from pathlib import Path

# Add the project root to sys.path so it can find 'app'
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

# Load environment before local imports
from dotenv import load_dotenv
# Point to app/.env relative to the scripts folder
load_dotenv(Path(__file__).resolve().parent.parent / "app" / ".env")

import requests
from app.database import SessionLocal
from app.models import Recording, Meeting
from app.crud import mark_recording_media_expired
from app.services.recall_service import delete_bot_media

logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

def main():
    parser = argparse.ArgumentParser(description="Expire media from Recall API and nullify DB fields.")
    parser.add_argument("--limit", type=int, default=None, help="Maximum number of records to process. If not given, processes all.")
    args = parser.parse_args()

    db = SessionLocal()
    try:
        query = db.query(Recording)
        recordings = query.all()
        logger.info(f"Found {len(recordings)} total recordings in database.")
        
        processed_count = 0
        for recording in recordings:
            if args.limit is not None and processed_count >= args.limit:
                logger.info(f"Reached the requested limit of {args.limit} records. Stopping.")
                break
                
            if recording.is_media_expired:
                logger.info(f"Recording {recording.id} is already marked as expired in DB. Skipping.")
                continue
                
            if not recording.recall_recording_id:
                logger.info(f"Recording {recording.id} has no recall_recording_id. Skipping.")
                continue

            meeting = db.query(Meeting).filter(Meeting.id == recording.meeting_id).first()
            if not meeting or not meeting.recall_bot_id:
                logger.warning(f"Recording {recording.id} missing meeting or recall_bot_id. Skipping.")
                continue

            terminal_statuses = ["completed", "bot.call_ended", "bot.done", "transcript.done", "bot.fatal", "abort", "not_admitted", "too_short", "recording.failed", "transcript.failed", "recording.done"]
            if meeting.status not in terminal_statuses:
                logger.warning(f"Recording {recording.id} belongs to a bot that is still active (status: {meeting.status}). Skipping so we don't abort it.")
                continue

            # Increment the counter because we are actively attempting to process this record
            processed_count += 1

            logger.info(f"Processing Recording {recording.id} (Bot ID: {meeting.recall_bot_id})...")
            try:
                # Use the exact Recall API endpoint to delete media artifacts
                delete_bot_media(meeting.recall_bot_id)
                logger.info(f"Successfully deleted media for bot {meeting.recall_bot_id} from Recall API.")
            except requests.exceptions.RequestException as exc:
                status_code = getattr(exc.response, "status_code", None)
                if status_code == 404:
                    logger.info(f"Bot {meeting.recall_bot_id} is already deleted from Recall (404 Not Found). Proceeding to clean DB.")
                else:
                    logger.error(f"Failed to delete media for bot {meeting.recall_bot_id} from Recall: {exc}")
                    logger.warning(f"Skipping DB updates for Recording {recording.id} due to API failure.")
                    continue

            # Mark as expired in our DB, which sets the required fields to null
            # and sets is_media_expired = True
            mark_recording_media_expired(db, meeting.id)
            logger.info(f"Successfully nullified download URLs and set is_media_expired=True for Recording {recording.id}.")

    finally:
        db.close()
    
    logger.info("Script completed.")

if __name__ == "__main__":
    main()
