import browser_cookie3
import http.cookiejar as cookiejar

class CookiesExtractor:

    def export_cookies_jar(self, domain: str | None = None):
        """
        Export cookies từ Google Chrome ra MozillaCookieJar object (Netscape format)

        :param domain: ví dụ "youtube.com" để lọc cookie
        """
        cj = cookiejar.MozillaCookieJar()

        # 🔒 Chỉ đọc cookies từ Chrome
        cookies = browser_cookie3.chrome(domain_name=domain)

        for c in cookies:
            ck = cookiejar.Cookie(
                version=0,
                name=c.name,
                value=c.value,
                port=None,
                port_specified=False,
                domain=c.domain,
                domain_specified=True,
                domain_initial_dot=c.domain.startswith("."),
                path=c.path,
                path_specified=True,
                secure=c.secure,
                expires=c.expires,
                discard=False,
                comment=None,
                comment_url=None,
                rest={"HttpOnly": c.has_nonstandard_attr("HttpOnly")},
                rfc2109=True,
            )
            cj.set_cookie(ck)

        return cj

    def export_cookies_txt(self,
        output_file: str = "cookies.txt",
        domain: str | None = None,
    ):
        """
        Export cookies từ Google Chrome ra file cookies.txt (Netscape format)

        :param output_file: đường dẫn file output
        :param domain: ví dụ "youtube.com" để lọc cookie
        """
        cj = self.export_cookies_jar(domain=domain)
        cj.save(output_file, ignore_discard=True, ignore_expires=True)
        print(f"✅ Chrome cookies saved to {output_file}")

    def export_cookies_str(self, domain: str | None = None) -> str:
        return self._cookiejar_to_string(self.export_cookies_jar(domain=domain))

    def _cookiejar_to_string(self, cj: cookiejar.MozillaCookieJar) -> str:
        import tempfile
        with tempfile.NamedTemporaryFile(mode="w+", delete=True) as f:
            cj.save(f.name, ignore_discard=True, ignore_expires=True)
            f.seek(0)
            return f.read()
