import logging
import random
from collections import OrderedDict
from . import BasePlugin
from ..fingerprints import get_profile

logger = logging.getLogger("nebulascrape.plugins.header_optimizer")


class HeaderOptimizerPlugin(BasePlugin):
    name = "header_optimizer"
    priority = 20

    def __init__(self, profile_name: str = "chrome_windows", rotate_ua: bool = False):
        self._profile_name = profile_name
        self._rotate_ua = rotate_ua

    def on_pre_request(self, scraper, method, url, kwargs):
        current_headers = kwargs.get("headers", {}) or {}
        profile = get_profile(self._profile_name)
        base_headers = OrderedDict(profile["headers"])

        merged = OrderedDict()
        for k, v in base_headers.items():
            if k.lower() not in {h.lower() for h in current_headers}:
                merged[k] = v
        merged.update(current_headers)

        if method.upper() in ("POST", "PUT", "PATCH"):
            merged.setdefault("Content-Type", "application/x-www-form-urlencoded")
            merged.pop("Upgrade-Insecure-Requests", None)
            merged["Sec-Fetch-Mode"] = "cors"
            merged["Sec-Fetch-Site"] = "same-origin"

        kwargs["headers"] = merged
        return kwargs
