"""Website resource relocation must not relocate runtime or public URLs."""
import re
from pathlib import Path

import pytest

from modules.core import storage_paths

ROOT = Path(__file__).resolve().parents[2]
WEBSITE = ROOT / 'InvestmentWebsite'


def test_flask_serves_every_versioned_asset_at_the_original_url(client):
    assets = list((WEBSITE / 'static').rglob('*'))
    for asset in assets:
        if not asset.is_file():
            continue
        relative = asset.relative_to(WEBSITE / 'static').as_posix()
        response = client.get('/static/' + relative)
        assert response.status_code == 200, relative
        assert response.data == asset.read_bytes(), relative


def test_global_loader_finds_all_website_and_manager_templates(app):
    for folder in (WEBSITE / 'templates', ROOT / 'InvestmentManager/templates'):
        for template in folder.rglob('*.html'):
            name = template.relative_to(folder).as_posix()
            assert app.jinja_env.get_template(name), name
    assert app.jinja_env.get_template('sitemap.xml')


def test_relative_es_module_imports_stay_inside_the_relocated_tree():
    base = WEBSITE / 'static/js'
    for script in base.rglob('*.js'):
        text = script.read_text(encoding='utf-8-sig')
        imports = re.findall(r'''(?:from\s*|import\s*\(\s*|import\s*)['"](\.[^'"]+)['"]''', text)
        for name in imports:
            path = (script.parent / name).resolve()
            assert path.is_relative_to(base), (script, name)
            assert path.is_file(), (script, name)


@pytest.mark.parametrize('external', [False, True])
def test_design_and_runtime_roots_remain_separate(tmp_path, monkeypatch, external):
    checkout = tmp_path / 'checkout'
    data = tmp_path / 'private-data'
    monkeypatch.setattr(storage_paths, 'REPO_ROOT', checkout)
    monkeypatch.setenv('INVESTMENT_LEGACY_STORAGE', '1')
    if external:
        monkeypatch.setenv('DATA_DIR', str(data))
    else:
        monkeypatch.delenv('DATA_DIR', raising=False)
    monkeypatch.chdir(tmp_path)
    assert storage_paths.static_dir() == checkout / 'InvestmentWebsite/static'
    assert storage_paths.images_dir() == checkout / 'InvestmentWebsite/static/images'
    assert storage_paths.static_data_dir() == checkout / 'InvestmentWebsite/static/data'
    assert storage_paths.offer_dir(7) == (data / 'offers/7' if external else checkout / 'static/images/7')
    assert storage_paths.agent_avatar_dir() == (data / 'agents' if external else checkout / 'static/images')
    assert not list(tmp_path.iterdir())


@pytest.mark.parametrize('external', [False, True])
def test_media_routes_keep_old_urls_and_deny_private_runtime(client, tmp_path, monkeypatch, external):
    monkeypatch.setattr(storage_paths, 'REPO_ROOT', tmp_path / 'checkout')
    monkeypatch.setenv('INVESTMENT_LEGACY_STORAGE', '1')
    if external:
        monkeypatch.setenv('DATA_DIR', str(tmp_path / 'private-data'))
    else:
        monkeypatch.delenv('DATA_DIR', raising=False)
    offer = storage_paths.offer_dir(7)
    offer.mkdir(parents=True)
    (offer / 'image_7_url_1.JPG').write_bytes(b'synthetic-jpeg')
    (offer / 'notes.md').write_text('private', encoding='utf8')
    avatars = storage_paths.agent_avatar_dir()
    avatars.mkdir(parents=True, exist_ok=True)
    (avatars / 'agent_9.jpg').write_bytes(b'synthetic-avatar')
    assert client.get('/static/images/7/image_7_url_1.JPG').data == b'synthetic-jpeg'
    assert client.get('/static/images/agent_9.jpg').data == b'synthetic-avatar'
    assert client.get('/static/images/7/notes.md').status_code == 404
    assert client.get('/static/images/7/../notes.md').status_code == 404
    assert client.get('/static/images/investment_logo.webp').status_code == 200


def test_seo_reads_lastmod_from_relocated_template(monkeypatch, tmp_path):
    import os
    from datetime import datetime
    from InvestmentWebsite import seo

    template = tmp_path / 'InvestmentWebsite/templates/strona_glowna.html'
    template.parent.mkdir(parents=True)
    template.write_text('synthetic', encoding='utf8')
    stamp = 1609459200
    os.utime(template, (stamp, stamp))
    monkeypatch.setattr(seo, 'BASE_DIR', str(tmp_path))
    assert seo._template_lastmod('', 'fallback') == datetime.utcfromtimestamp(stamp).date().isoformat()


def test_error_templates_and_crm_static_keep_their_urls(client):
    assert client.get('/not-a-real-stage3-page').status_code == 404
    response = client.get('/crm/crm-static/js/export_packages.js')
    assert response.status_code == 200
    assert response.data == (ROOT / 'InvestmentManager/static/js/export_packages.js').read_bytes()


def test_cache_busting_reads_relocated_asset_and_preserves_legacy_runtime(app, tmp_path, monkeypatch):
    from flask import url_for
    from InvestmentWebsite import assets

    legacy = tmp_path / 'static/images/agent_9.jpg'
    legacy.parent.mkdir(parents=True)
    legacy.write_bytes(b'synthetic-avatar')
    monkeypatch.setattr(assets, 'BASE_DIR', str(tmp_path))

    with app.test_request_context('/'):
        assert url_for('static', filename='output.css') == '/static/output.css'
        # The existing context processor adds mtime, without changing the URL path.
        context = {}
        app.update_template_context(context)
        assert context['url_for']('static', filename='output.css').startswith('/static/output.css?')
        assert context['url_for']('static', filename='images/agent_9.jpg') == (
            '/static/images/agent_9.jpg?v=' + str(int(legacy.stat().st_mtime))
        )
        assert context['url_for']('static', filename='images/missing.jpg') == '/static/images/missing.jpg'
