"""Submit-wizard field surface (#17 visibility removal, #22 grant widget).

- Visibility is the KM officer's call, not the uploader's, so it must NOT appear
  on the submit form (it stays on the edit/QA forms).
- The grant reference is now driven by the RIMS grant picker (Phase 2.4) — a
  hidden field the combobox writes the chosen public_grant_id into, validated
  against active/closed funding records — not the interim free-text input.
"""
from __future__ import annotations

import pytest
from django import forms

from apps.repository.documents.forms import (
    DocumentMetadataEditForm,
    DocumentSubmitForm,
)


@pytest.mark.django_db
def test_submit_form_has_no_visibility_field():
    form = DocumentSubmitForm()
    assert "visibility" not in form.fields


@pytest.mark.django_db
def test_edit_form_still_exposes_visibility():
    # Visibility remains editable for curators on the metadata edit surface.
    form = DocumentMetadataEditForm()
    assert "visibility" in form.fields


@pytest.mark.django_db
def test_submit_form_grant_reference_is_picker_hidden_not_empty_select():
    # Phase 2.4 — the grant field is a hidden input the RIMS picker writes into,
    # never a bare (empty) <select> (#22, FRREP-MCL009).
    form = DocumentSubmitForm()
    widget = form.fields["grant_reference"].widget
    assert isinstance(widget, forms.HiddenInput)
    assert not isinstance(widget, forms.Select)


@pytest.mark.django_db
def test_submit_form_license_is_a_choice_dropdown():
    # #21 — license_type is a Select bound to the License (CC/OA) choices, not
    # a free-text input. license_notes is the only free-text licence field.
    form = DocumentSubmitForm()
    field = form.fields["license_type"]
    assert isinstance(field.widget, forms.Select)
    assert len(field.choices) > 1
    rendered = [label for _value, label in field.choices]
    assert any("CC" in str(lbl) or "Creative Commons" in str(lbl) for lbl in rendered)


@pytest.mark.django_db
def test_submit_form_ignores_posted_visibility(public_collection, submitter_user):
    # A stray visibility value in POST data must not bind — the field is gone.
    form = DocumentSubmitForm(
        data={
            "title": "T",
            "abstract": "A",
            "document_type": "thesis",
            "license_type": "cc_by",
            "language": "en",
            "year": 2026,
            "collection": public_collection.pk,
            "visibility": "public_open",
            "grant_reference": "",
            "authors_text": "Doe, Jane",
            "staged_token": "tok",
        }
    )
    assert form.is_valid(), form.errors
    assert "visibility" not in form.cleaned_data
