# #region TestCleanReleaseLegacyCompat [TYPE Module] [C:3] [SEMANTICS test, clean-release, legacy, compat]
# @RELATION BINDS_TO -> SrcRoot
# @BRIEF Compatibility tests for legacy clean-release API paths retained during v2 migration.
# @LAYER Tests
from __future__ import annotations

from datetime import UTC, datetime
import os

from fastapi.testclient import TestClient

os.environ.setdefault("DATABASE_URL", "sqlite:///./test_clean_release_legacy_compat.db")
os.environ.setdefault(
    "AUTH_DATABASE_URL", "sqlite:///./test_clean_release_legacy_auth.db"
)
from src.app import app
from src.dependencies import get_clean_release_repository
from src.models.clean_release import (
    CleanProfilePolicy,
    DistributionManifest,
    ProfileType,
    ReleaseCandidate,
    ReleaseCandidateStatus,
    ResourceSourceEntry,
    ResourceSourceRegistry,
)
from src.services.clean_release.repository import CleanReleaseRepository


# #region _seed_legacy_repo [TYPE Function]
# @RELATION BINDS_TO -> TestCleanReleaseLegacyCompat
# @BRIEF Seed in-memory repository with minimum trusted data for legacy endpoint contracts.
# @PRE  Repository is empty.
# @POST  Candidate, policy, registry and manifest are available for legacy checks flow.
def _seed_legacy_repo() -> CleanReleaseRepository:
    repo = CleanReleaseRepository()
    now = datetime.now(UTC)
    repo.save_candidate(
        ReleaseCandidate(
            id="legacy-rc-001",
            version="1.0.0",
            source_snapshot_ref="git:legacy-001",
            created_at=now,
            created_by="compat-tester",
            status=ReleaseCandidateStatus.DRAFT,
        )
    )
    registry = ResourceSourceRegistry(
        registry_id="legacy-reg-1",
        name="Legacy Internal Registry",
        entries=[
            ResourceSourceEntry(
                source_id="legacy-src-1",
                host="repo.intra.company.local",
                protocol="https",
                purpose="artifact-repo",
                enabled=True,
            )
        ],
        updated_at=now,
        updated_by="compat-tester",
        status="ACTIVE",
    )
    registry.immutable = True
    registry.allowed_hosts = ["repo.intra.company.local"]
    registry.allowed_schemes = ["https"]
    registry.allowed_source_types = ["artifact-repo"]
    repo.save_registry(registry)
    policy = CleanProfilePolicy(
        policy_id="legacy-pol-1",
        policy_version="1.0.0",
        profile=ProfileType.ENTERPRISE_CLEAN,
        active=True,
        internal_source_registry_ref="legacy-reg-1",
        prohibited_artifact_categories=["test-data"],
        required_system_categories=["core"],
        effective_from=now,
    )
    policy.immutable = True
    policy.content_json = {"profile": "enterprise-clean", "prohibited_artifact_categories": ["test-data"], "required_system_categories": ["core"], "external_source_forbidden": True}
    repo.save_policy(policy)
    repo.save_manifest(
        DistributionManifest(
            id="legacy-manifest-1",
            candidate_id="legacy-rc-001",
            manifest_version=1,
            manifest_digest="sha256:legacy-manifest",
            artifacts_digest="sha256:legacy-artifacts",
            created_at=now,
            created_by="compat-tester",
            source_snapshot_ref="git:legacy-001",
            content_json={
                "items": [],
                "summary": {"included_count": 0, "prohibited_detected_count": 0},
            },
            immutable=True,
        )
    )
    return repo
# #endregion _seed_legacy_repo
# #region test_legacy_prepare_endpoint_still_available [TYPE Function]
# @RELATION BINDS_TO -> TestCleanReleaseLegacyCompat
# @BRIEF Verify legacy prepare endpoint remains reachable and returns a status payload.
def test_legacy_prepare_endpoint_still_available() -> None:
    repo = _seed_legacy_repo()
    app.dependency_overrides[get_clean_release_repository] = lambda: repo
    try:
        client = TestClient(app)
        response = client.post(
            "/api/clean-release/candidates/prepare",
            json={
                "candidate_id": "legacy-rc-001",
                "artifacts": [
                    {"path": "src/main.py", "category": "core", "reason": "required"}
                ],
                "sources": ["repo.intra.company.local"],
                "operator_id": "compat-tester",
            },
        )
        assert response.status_code == 200
        payload = response.json()
        assert "status" in payload
        assert payload["status"] in {"prepared", "blocked", "PREPARED", "BLOCKED"}
    finally:
        app.dependency_overrides.clear()
# #endregion test_legacy_prepare_endpoint_still_available
# #region test_legacy_checks_endpoints_still_available [TYPE Function]
# @RELATION BINDS_TO -> TestCleanReleaseLegacyCompat
# @BRIEF Verify legacy checks start/status endpoints remain available during v2 transition.
def test_legacy_checks_endpoints_still_available() -> None:
    repo = _seed_legacy_repo()
    app.dependency_overrides[get_clean_release_repository] = lambda: repo
    try:
        client = TestClient(app)
        start_response = client.post(
            "/api/clean-release/checks",
            json={
                "candidate_id": "legacy-rc-001",
                "profile": "enterprise-clean",
                "execution_mode": "api",
                "triggered_by": "compat-tester",
            },
        )
        assert start_response.status_code == 202
        start_payload = start_response.json()
        assert "check_run_id" in start_payload
        assert start_payload["candidate_id"] == "legacy-rc-001"
        status_response = client.get(
            f"/api/clean-release/checks/{start_payload['check_run_id']}"
        )
        assert status_response.status_code == 200
        status_payload = status_response.json()
        assert status_payload["check_run_id"] == start_payload["check_run_id"]
        assert "final_status" in status_payload
        assert "checks" in status_payload
    finally:
        app.dependency_overrides.clear()
# #endregion test_legacy_checks_endpoints_still_available
# #endregion TestCleanReleaseLegacyCompat
