# ============================================================
# src/accountable_record/stage_020_contract/load.py
# ============================================================
"""Read the contract declaration from a target manifest.

WHY:
    Stage 020 interprets the schema-valid [contract] table according to the
    repository class. Contract repositories declare contract authority fields.
    Implementation repositories declare which contract they consume.
"""

from pathlib import Path

from accountable_record.stage_010_identity.base.constants import (
    allowed_manifest_filenames,
)
from accountable_record.stage_010_identity.manifest import load_manifest_data
from accountable_record.stage_020_contract.base.scalars import (
    optional_bool,
    optional_string,
    required_string,
    required_table,
)
from accountable_record.stage_020_contract.model import ContractDeclaration


def find_manifest_path(repo_root: Path) -> Path:
    """Return the manifest path in repo_root, or raise FileNotFoundError."""
    for name in allowed_manifest_filenames():
        candidate = repo_root / name
        if candidate.is_file():
            return candidate

    allowed = ", ".join(allowed_manifest_filenames())
    msg = f"No manifest found in {repo_root} (looked for: {allowed})"
    raise FileNotFoundError(msg)


def read_contract_declaration(
    repo_root: Path,
    *,
    repo_class: str,
) -> ContractDeclaration:
    """Read the schema-valid contract declaration for this repository class."""
    manifest_filename, manifest = load_manifest_data(repo_root)
    contract = required_table(manifest, "contract", "SE_MANIFEST.toml")

    if repo_class == "contract":
        return ContractDeclaration(
            source_path=repo_root / manifest_filename,
            repo_class=repo_class,
            consumes_contract_from=None,
            contract_version=required_string(
                contract,
                "contract_version",
                "[contract]",
            ),
            contract_role=required_string(
                contract,
                "contract_role",
                "[contract]",
            ),
            contract_authority=required_string(
                contract,
                "contract_authority",
                "[contract]",
            ),
            exports_verified_contract=optional_bool(
                contract,
                "exports_verified_contract",
            ),
        )

    return ContractDeclaration(
        source_path=repo_root / manifest_filename,
        repo_class=repo_class,
        consumes_contract_from=required_string(
            contract,
            "consumes_contract_from",
            "[contract]",
        ),
        contract_version=optional_string(contract, "contract_version"),
        contract_role=optional_string(contract, "contract_role"),
        contract_authority=optional_string(contract, "contract_authority"),
        exports_verified_contract=optional_bool(
            contract,
            "exports_verified_contract",
        ),
    )
