"""Persistent cookie jar for session-based scraping."""

import json
import os
import time
import logging
from http.cookiejar import MozillaCookieJar, Cookie
from pathlib import Path

logger = logging.getLogger("iploop.cookies")


class CookieManager:
    """Manages cookies across requests for realistic browsing behavior."""
    
    def __init__(self, persist_path=None):
        """
        Args:
            persist_path: Path to save cookies (None = in-memory only)
        """
        self._jar = MozillaCookieJar()
        self._persist_path = persist_path
        if persist_path and os.path.exists(persist_path):
            try:
                self._jar.load(persist_path, ignore_discard=True, ignore_expires=True)
                logger.debug(f"Loaded {len(self._jar)} cookies from {persist_path}")
            except Exception as e:
                logger.debug(f"Could not load cookies: {e}")
    
    @property
    def jar(self):
        """Get the cookie jar for use with requests."""
        return self._jar
    
    def save(self):
        """Save cookies to disk."""
        if self._persist_path:
            try:
                os.makedirs(os.path.dirname(self._persist_path) or '.', exist_ok=True)
                self._jar.save(self._persist_path, ignore_discard=True, ignore_expires=True)
            except Exception as e:
                logger.debug(f"Could not save cookies: {e}")
    
    def clear(self, domain=None):
        """Clear cookies, optionally for a specific domain."""
        if domain:
            self._jar.clear(domain)
        else:
            self._jar.clear()
        self.save()
    
    def count(self):
        """Number of cookies stored."""
        return len(self._jar)
    
    def domains(self):
        """List domains with cookies."""
        return list(set(c.domain for c in self._jar))
    
    def __len__(self):
        return len(self._jar)
