"""Core-owned persistence for project-scoped L3 candidates."""
from __future__ import annotations

from typing import Any
from uuid import UUID

from sqlalchemy.ext.asyncio import AsyncSession

from src.domain.l3_registry.repository import L3CandidateRepository


async def record_codegen_candidates(
    db: AsyncSession,
    *,
    project_id: UUID,
    generation_run_id: UUID,
    commit_sha: str | None,
    candidates: list[dict[str, Any]] | None,
) -> list[str]:
    """Idempotently record only Core-declared project L3 candidates."""
    repo = L3CandidateRepository(db)
    recorded: list[str] = []
    for item in candidates or []:
        if not isinstance(item, dict):
            continue
        candidate_id = str(item.get("candidate_id") or "").strip()
        semantic = str(item.get("semantic") or "").strip()
        if not candidate_id or not semantic:
            continue
        if not candidate_id.endswith(f"@project:{project_id}"):
            continue
        existing = await repo.get_by_external_id(candidate_id)
        if existing:
            recorded.append(candidate_id)
            continue
        await repo.create(
            candidate_id=candidate_id,
            semantic=semantic,
            project_id=project_id,
            generation_run_id=generation_run_id,
            scope="project",
            requirement_summary=str(item.get("requirement_summary") or semantic),
            gap_reason=str(item.get("gap_reason") or "semantic_gap"),
            architecture_manifest_sha=None,
            proposed_contract={},
            dependencies=[str(value) for value in item.get("dependencies") or []],
            evidence={"source": "core_generation_plan", "commit_sha": commit_sha},
            source_locations=[],
            commit_sha=commit_sha,
            version="0.1.0",
            promotion_candidate=False,
        )
        recorded.append(candidate_id)
    return recorded


__all__ = ["record_codegen_candidates"]
