import requests
from urllib.parse import urlparse
from typing import Optional
from .core import ValleyDamSigner

class ValleyDamSession(requests.Session):
    """
    A Requests Session that automatically signs every outgoing request
    with a ValleyDam Identity.
    """

    def __init__(self, domain: str, private_key_path: str):
        super().__init__()
        self.domain = domain
        self.signer = ValleyDamSigner(private_key_path)

    def request(self, method: str, url: str, *args, **kwargs):
        """
        Overrides the standard request method to inject authentication headers.
        """
        # Parse URL to get signing components
        parsed = urlparse(url)
        host = parsed.netloc 
        path = parsed.path if parsed.path else "/"

        # Generate Signature
        headers = self.signer.sign(method, host, path)
        
        # Add Identity Pointer
        headers['X-ValleyDam-KeyID'] = f"dns:{self.domain}"

        # Merge with user-provided headers
        if 'headers' not in kwargs:
            kwargs['headers'] = {}
        kwargs['headers'].update(headers)

        return super().request(method, url, *args, **kwargs)