from pathlib import Path

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


def read(path: str) -> str:
    return (ROOT / path).read_text(encoding='utf-8')


def test_operations_links_preserve_return_to_context():
    operations = read('app/admin_ui/pages/operations.py')
    assert 'return_to = f"/operations?scope=' in operations
    assert 'return_to={quote(return_to' in operations
    assert 'primary_href.startswith(\'/tasks/\')' in operations


def test_task_detail_has_generic_return_link_and_safe_redirect():
    tasks = read('app/admin_ui/pages/tasks.py')
    assert '_safe_return_to' in tasks
    assert '← Voltar' in tasks
    assert 'Voltar ao Centro de trabalho atualizado' not in tasks
    assert 'HX-Redirect' in tasks
    assert 'name="return_to"' in tasks
    assert 'return_to = _safe_return_to(str(form.get("return_to")' in tasks


def test_return_to_accepts_caller_contexts():
    tasks = read('app/admin_ui/pages/tasks.py')
    assert '"/operations"' in tasks
    assert '"/tasks"' in tasks
    assert '"/opportunities"' in tasks


def test_task_links_preserve_origin_from_tasks_and_opportunities():
    tasks = read('app/admin_ui/pages/tasks.py')
    opportunities = read('app/admin_ui/pages/opportunities.py')
    assert '_tasks_list_return_to' in tasks
    assert '_task_href(task_id, return_to)' in tasks
    assert 'render_tasks_list_partial(tasks, return_to=return_to)' in tasks
    assert '_task_href_with_return_to' in opportunities
    assert 'opportunity_return_to = f"/opportunities/{opportunity_id}"' in opportunities
