from packages.adapters.in_memory import InMemoryClassificationJobRepository
from packages.application import (
    SubmitClassificationJobCommand,
    SubmitClassificationJobUseCase,
)
from packages.domain import AssetClassification, ClassificationJobStatus


def simulate_classify_asset(job_id: str, job_repo: InMemoryClassificationJobRepository) -> dict:
    """Simulate classification logic without Celery."""
    job = job_repo.get(job_id)
    if job is None:
        return {"status": "failed", "error": "job not found"}

    try:
        # Update job status to PROCESSING
        job.status = ClassificationJobStatus.PROCESSING
        job_repo.update(job)

        # Mock classification
        asset_id_hash = sum(ord(c) for c in job.asset_id)
        classifications = list(AssetClassification)
        classification = classifications[asset_id_hash % len(classifications)]
        confidence = 0.85

        # Update job status to COMPLETED
        job.status = ClassificationJobStatus.COMPLETED
        job.classification = classification.value
        job.confidence = confidence
        job_repo.update(job)

        return {
            "status": "completed",
            "job_id": job.id,
            "classification": classification.value,
            "confidence": confidence,
        }
    except Exception as e:
        # Update job status to FAILED
        job.status = ClassificationJobStatus.FAILED
        job.error_message = str(e)
        job_repo.update(job)

        return {
            "status": "failed",
            "job_id": job.id,
            "error": str(e),
        }


def test_classification_pipeline():
    """Test the full classification pipeline: submit job -> worker processes -> result."""
    job_repo = InMemoryClassificationJobRepository()

    # Submit classification job
    use_case = SubmitClassificationJobUseCase(job_repo)
    job = use_case.execute(
        SubmitClassificationJobCommand(
            project_id="proj-1",
            asset_id="asset-123",
        )
    )

    assert job.status == ClassificationJobStatus.PENDING
    assert job.classification == ""
    assert job.confidence == 0.0

    # Simulate worker task execution
    result = simulate_classify_asset(job.id, job_repo)

    assert result["status"] == "completed"
    assert "classification" in result
    assert "confidence" in result

    # Verify job was updated
    updated_job = job_repo.get(job.id)
    assert updated_job is not None
    assert updated_job.status == ClassificationJobStatus.COMPLETED
    assert updated_job.classification != ""
    assert updated_job.confidence > 0.0
