from __future__ import annotations

from typing import Any

from .client import AppraisalForgeClient
from .config import load_fill_config, parse_property_config


def run_fill(
    client: AppraisalForgeClient,
    config_path: str,
    appraisal_id: int | None = None,
    dry_run: bool = False,
) -> dict[str, Any]:
    config = load_fill_config(config_path)
    props = parse_property_config(str(config.get("property_config", "")))

    created = False
    if appraisal_id is None:
        subject_address = str(config.get("subject_address") or props.get("ADDRESS") or "").strip()
        report_name = str(config.get("report_name") or subject_address or "SDK Fill").strip()
        if not subject_address:
            raise ValueError("subject_address is required when --appraisal-id is not provided")

        if dry_run:
            appraisal_id = -1
        else:
            created_resp = client.create_appraisal(report_name, subject_address)
            appraisal_id = int(created_resp["id"])
            created = True

    fields = config.get("uad_fields") or {}
    if not isinstance(fields, dict):
        raise ValueError("uad_fields must be an object of field_id -> value")

    written = 0
    if fields and not dry_run:
        client.write_fields(appraisal_id, fields)
        written = len(fields)

    validation: dict[str, Any] | None = None
    if config.get("validate_after", True) and not dry_run:
        validation = client.validate(appraisal_id)

    return {
        "appraisal_id": appraisal_id,
        "created": created,
        "dry_run": dry_run,
        "fields_requested": len(fields),
        "fields_written": written,
        "validation": validation,
    }
