from packages.adapters.in_memory import (
    InMemoryAssetRepository,
    InMemoryIngestJobRepository,
)
from packages.application import SubmitIngestJobCommand, SubmitIngestJobUseCase
from packages.domain import IngestJobStatus


def simulate_upload_and_ingest(
    project_id: str,
    library_id: str,
    filename: str,
    job_repo: InMemoryIngestJobRepository,
    asset_repo: InMemoryAssetRepository,
) -> dict:
    """Simulate full upload → ingest pipeline."""
    from uuid import uuid4

    from tests.integration.test_ingest_pipeline import simulate_ingest_asset

    # Mock storage: generate storage_key
    storage_key = f"uploads/{uuid4().hex[:8]}/{filename}"

    # Submit ingest job
    use_case = SubmitIngestJobUseCase(job_repo)
    job = use_case.execute(
        SubmitIngestJobCommand(
            project_id=project_id,
            library_id=library_id,
            storage_key=storage_key,
        )
    )

    # Simulate worker task
    result = simulate_ingest_asset(job.id, job_repo, asset_repo)

    return {
        "storage_key": storage_key,
        "job_id": job.id,
        "worker_result": result,
    }


def test_upload_to_asset_full_pipeline():
    """Test full pipeline: upload → storage → ingest job → worker → asset created."""
    job_repo = InMemoryIngestJobRepository()
    asset_repo = InMemoryAssetRepository()

    # Simulate upload
    result = simulate_upload_and_ingest(
        project_id="proj-1",
        library_id="lib-1",
        filename="demo-video.mp4",
        job_repo=job_repo,
        asset_repo=asset_repo,
    )

    assert "storage_key" in result
    assert result["storage_key"].endswith("demo-video.mp4")
    assert result["worker_result"]["status"] == "completed"

    # Verify job was completed
    job = job_repo.get(result["job_id"])
    assert job is not None
    assert job.status == IngestJobStatus.COMPLETED
    assert job.result_asset_id != ""

    # Verify asset was created
    assets = asset_repo.list_by_library("lib-1")
    assert len(assets) == 1
    assert assets[0].name == "demo-video.mp4"
    assert assets[0].storage_key == result["storage_key"]
