# import socket
# import sys
# import re
# from ipaddress import IPv4Address
# from datetime import datetime
# import mysql.connector
# import json
# import requests
# import pandas as pd
# import os
# import logging
# try:
#     import geoip2.database
#     from geoip2.errors import AddressNotFoundError
#     geoip2_available = True
# except ImportError:
#     geoip2_available = False


# class OpenVPNMonitor:
#     def __init__(self, server_ip, server_port, data_limit_mb, log_file='disconnect_log.csv'):
#         self.server_ip = server_ip
#         self.server_port = server_port
#         self.data_limit_bytes = data_limit_mb * 1024 * 1024
#         self.s = None  
#         self.log_file = log_file
#         self.connected_servers = []
#         self.gi = geoip2.database.Reader('/var/www/html/1375-staysolid-ovpn-backend/GeoLite2-City.mmdb')
#         self.geoip_version = 2

#     def _socket_recv(self, length):
#         if sys.version_info[0] == 2:
#             return self.s.recv(length)
#         else:
#             return self.s.recv(length).decode('utf-8')


#     def connect(self):
#         print('in connect')
#         try:
#             self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#             self.s.connect((self.server_ip, self.server_port))
#             print(f"Connected to OpenVPN management interface at {self.server_ip}:{self.server_port}")
#         except Exception as e:
#             print(f"Error connecting to OpenVPN management: {e}")

#     def get_status(self):
#         try:
#             if not self.s:
#                 print("Socket is not connected!")
#                 return None
            
#             self.s.sendall(b"status\n")
            
#             data = ''
#             while True:
#                 socket_data = self._socket_recv(4096)
#                 # print(socket_data)
#                 if not socket_data:
#                     break
                
#                 socket_data = re.sub(r'>INFO(.)*\r\n', '', socket_data)
#                 data += socket_data
                
#                 if 'END' in socket_data:
#                     break

#             if not data:
#                 print("Received empty data from server.")
#                 return None
            
#             return data
#         except Exception as e:
#             print(f"Error receiving data: {e}")
#             return None
        
#     def fetch_data_once(self):
#         data = self.get_status()
#         print(data)

# if __name__ == "__main__":

#     vpn_monitor = OpenVPNMonitor("172.245.234.181", 5555, data_limit_mb=10000)
#     vpn_monitor.connect()
#     structured_data = vpn_monitor.fetch_data_once()
#     if structured_data:
#         logging.info(structured_data)
#         logging.info('=======================================')
#         # print(structured_data)
# import pymysql

# # Database connection details
# db_config = {
#     "host": "ovpn-centrealised-server.cl66yeq0k0b7.us-east-2.rds.amazonaws.com",
#     "user": "xeg3ua7ooqu1",
#     "password": "ahv3eigee2zo",
#     "database": "xeg3ua7ooqu12"
# }

# try:
#     # Establish a database connection
#     connection = pymysql.connect(**db_config,cursorclass=pymysql.cursors.DictCursor)

#     with connection.cursor() as cursor:
#         # Write your SQL query
#         sql_query = "SELECT * FROM ovpn_server_logs LIMIT 500"
#         cursor.execute(sql_query)
        
#         # Fetch all rows
#         results = cursor.fetchall()

#         # Print results
#         # for row in results:
#         #     print(results)
#         print(results)

# except pymysql.MySQLError as e:
#     print(f"Error: {e}")

# finally:
#     if connection:
#         connection.close()

# import instaloader

# # Create an instance of Instaloader
# L = instaloader.Instaloader()

# # Download profile pictures and posts
# username = "hey.khushbu"
# L.download_profile(username, profile_pic_only=False)



# import instaloader
# import os
# import shutil

# def download_reel(index):
#     L = instaloader.Instaloader()

#     # Extract the shortcode from the URL
#     # url = "https://www.instagram.com/reel/DFuvscoI3hT/"
#     url = "https://instagram.com/p/DAUs9AQMv63/"
#     shortcode = url.split("/")[-2]  # Extracts "DFuvscoI3hT"

#     # Get the post
#     post = instaloader.Post.from_shortcode(L.context, shortcode)

#     # Download the reel (It will save with default naming)
#     L.download_post(post, target="reels_download")

#     # Find the downloaded video file
#     for filename in os.listdir("reels_download"):
#         if filename.endswith(".mp4"):  # Look for the downloaded MP4 file
#             old_path = os.path.join("reels_download", filename)
#             new_path = os.path.join("reels_download", f"{index}.mp4")
#             shutil.move(old_path, new_path)  # Rename the file
#             print(f"Saved: {new_path}")
#             break

# # Download the reel 100 times
# for i in range(1, 101):
#     download_reel(i)


# import instaloader


# L = instaloader.Instaloader()

# # Extract the shortcode from the URL
# url = "https://www.instagram.com/reel/DFAsouPyOH_/?igsh=ang1NTdqOTIwOTkx"
# shortcode = url.split("/")[-2]  # Extracts "DFuvscoI3hT"

# # Get the post
# post = instaloader.Post.from_shortcode(L.context, shortcode)

# # Download the reel
# L.download_post(post, target="reels_download")


# import yt_dlp

# # Instagram Reel URL
# reel_url = "https://www.instagram.com/share/reel/BAFyPdp51j" 

# # Download options
# options = {
#     "outtmpl": "%(title)s.%(ext)s",
#     "format": "bestvideo+bestaudio/best",
# }

# with yt_dlp.YoutubeDL(options) as ydl:
#     ydl.download([reel_url])

# print("Download completed!")

import yt_dlp

def download_instagram_reel(url):
    """Downloads an Instagram Reel using yt-dlp"""
    ydl_opts = {
        'outtmpl': 'instagram_reel.%(ext)s',
        'format': 'bestvideo+bestaudio/best',
        'cookies': '/var/www/html/1375-staysolid-ovpn-backend/cookies.txt',
    }
    
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

if __name__ == "__main__":
    reel_url = input("🔗 Enter Instagram Reel Link: ")
    download_instagram_reel(reel_url)
    print("✅ Download complete! File saved as 'instagram_reel.mp4'")
