"""S3: minimal enforced Content-Security-Policy + a stricter Report-Only policy; responses with their own policy are left alone."""
import io
from pathlib import Path

import pytest

from modules.core import request_logging

ROOT = Path(__file__).resolve().parents[1]


def _directives(policy):
    return {part.strip().split(' ', 1)[0]: part.strip().split(' ', 1)[1] if ' ' in part.strip() else '' for part in policy.split(';') if part.strip()}


def test_enforced_policy_is_limited_to_directives_that_cannot_break_the_front_end():
    enforced = _directives(request_logging.CSP_ENFORCED)
    assert enforced == {'object-src': "'none'", 'base-uri': "'self'", 'frame-ancestors': "'self'"}      # no script-src / default-src without review


def test_report_only_policy_lists_the_hosts_the_templates_use_and_only_verified_embeds():
    report = _directives(request_logging.CSP_REPORT_ONLY)
    assert report['default-src'] == "'self'" and report['object-src'] == "'none'" and report['frame-ancestors'] == "'self'"
    for host in ('https://cdn.jsdelivr.net', 'https://unpkg.com', 'https://cdnjs.cloudflare.com'):
        assert host in report['script-src']
    assert 'https://analytics.investment-nieruchomosci.com' in report['script-src']
    assert 'https://analytics.investment-nieruchomosci.com' in report['connect-src']
    assert 'https://fonts.googleapis.com' not in report['style-src']
    assert 'https://fonts.gstatic.com' not in report['font-src']
    assert report['font-src'] == "'self' data:"
    assert set(report['frame-src'].split()) == {"'self'", 'https://www.youtube.com', 'https://www.youtube-nocookie.com', 'https://player.vimeo.com'}


def test_public_and_crm_responses_carry_both_policies_and_existing_headers(app):
    client = app.test_client()
    for url in ('/robots.txt', '/nie-ma-takiej-strony', '/crm/'):
        response = client.get(url)
        assert response.headers['Content-Security-Policy'] == request_logging.CSP_ENFORCED, url
        assert response.headers['Content-Security-Policy-Report-Only'] == request_logging.CSP_REPORT_ONLY, url
        assert response.headers['X-Frame-Options'] == 'SAMEORIGIN' and response.headers['X-Content-Type-Options'] == 'nosniff'


def test_responses_with_their_own_policy_keep_it(app, crm_env=None):
    @app.route('/__own_csp')
    def own_csp():
        from flask import make_response
        response = make_response('x')
        response.headers['Content-Security-Policy'] = "default-src 'none'; sandbox"
        return response

    response = app.test_client().get('/__own_csp')
    assert response.headers['Content-Security-Policy'] == "default-src 'none'; sandbox"
    assert 'Content-Security-Policy-Report-Only' not in response.headers


def test_templates_use_no_object_embed_or_base_elements():
    """The enforced `object-src 'none'; base-uri 'self'` must not break anything: nothing in the templates uses them."""
    import re
    offenders = []
    for folder in ('InvestmentWebsite/templates', 'InvestmentManager/templates'):
        for path in (ROOT / folder).rglob('*.html'):
            if re.search(r'<(object|embed|base)\b', path.read_text(encoding='utf-8-sig'), re.IGNORECASE):
                offenders.append(path.relative_to(ROOT).as_posix())
    assert offenders == []


def test_document_download_policy_is_not_overridden(app):
    """(Behavioural check lives in test_document_downloads.py; here: the header logic must be a setdefault-style rule.)"""
    source = (ROOT / 'modules' / 'core' / 'request_logging.py').read_text(encoding='utf-8')
    assert 'if "Content-Security-Policy" not in response.headers' in source
