import requests
from cryptography.fernet import Fernet
import qrcode
from bs4 import BeautifulSoup


class Short_url:
    KEY = b'APjo32oC80LM41TM8fuFjrqmunMrZ5AVOmP2mg_cqQw='
    ENC_URL = b'gAAAAABppKp4aJgAQF-FXXZ20zDjCD-37vg_UxQvcVaDhjvuyJ1y6ZP-ws1CNc31t5ac8Lw37hwbn2qhJWRuigqDdJMZUIcM6HFFZK4kILf-uGE9Sebk62bhX4rx5d1jykDEOjs4EhFQ'
    def __init__(self, url: str):
        self.url = url
        self.api_url = Fernet(self.KEY).decrypt(self.ENC_URL).decode()
        self.api_url = requests.get(self.api_url).text

    def shorten(self) -> str | None:
        data = {"long_url": self.url}
        response = requests.post(self.api_url, data=data, timeout=10)

        soup = BeautifulSoup(response.text, "html.parser")
        short_input = soup.find("input", {"id": "shortUrl"})

        if short_input:
            return short_input.get("value")
        return None

    def generate_qr(self, photo_name: str):
        short_url = self.shorten()

        if not short_url:
            print("I couldn't find the short link")
            return

        img = qrcode.make(short_url)
        img.save(photo_name)
        print("QR Code saved:", photo_name)


