from starlette.testclient import TestClient
from pathlib import Path

from fmatch.saas.main import create_app


def test_put_local(tmp_path, monkeypatch):
    # Force local storage path
    from fmatch.saas import settings

    monkeypatch.setattr(settings, "STORAGE_BACKEND", "local", raising=False)
    monkeypatch.setattr(settings, "LOCAL_STORAGE_PATH", str(tmp_path), raising=False)

    client = TestClient(create_app())

    # Presign
    r = client.post("/api/v2/uploads/presign", json={"content_type": "text/csv"})
    assert r.status_code == 200, r.text
    data = r.json()
    object_id = data["object_id"]
    put_url = data["put_url"]

    # Extract URL path (strip scheme/host if present)
    if put_url.startswith("http"):
        # TestClient mounts at http://testserver
        from urllib.parse import urlparse

        pu = urlparse(put_url)
        put_path = pu.path + (f"?{pu.query}" if pu.query else "")
    else:
        put_path = put_url

    # Upload small CSV
    body = b"a,b\n1,2\n"
    r2 = client.put(put_path, data=body)
    assert r2.status_code == 200, r2.text

    # Verify file exists and content
    out_path = Path(settings.LOCAL_STORAGE_PATH) / object_id
    assert out_path.exists()
    assert out_path.read_bytes().startswith(b"a,b")

