from __future__ import annotations

import json
import os
import re
from pathlib import Path
from typing import Any

def _config_dir() -> Path:
    return Path(os.environ.get("APPRAISAL_FORGE_CONFIG_DIR", str(Path.home() / ".appraisal-forge")))


def _config_path() -> Path:
    return _config_dir() / "config.json"


def get_config_dir() -> Path:
    return _config_dir()


def load_fill_config(path: str) -> dict[str, Any]:
    data = json.loads(Path(path).read_text())
    if not isinstance(data, dict):
        raise ValueError("fill config must be a JSON object")
    return data


def parse_property_config(text: str) -> dict[str, str]:
    props: dict[str, str] = {}
    if not text:
        return props

    for raw in text.splitlines():
        line = raw.strip()
        if not line:
            continue

        if ":" in line:
            k, v = line.split(":", 1)
        elif "=" in line:
            k, v = line.split("=", 1)
        else:
            continue

        key = k.strip().upper().replace(" ", "_")
        val = v.strip()
        if val:
            props[key] = val

    if "ADDRESS" in props:
        parts = [p.strip() for p in props["ADDRESS"].split(",")]
        if len(parts) >= 3:
            props.setdefault("STREET", parts[0])
            props.setdefault("CITY", parts[1])
            last = parts[2]
            m = re.match(r"^([A-Za-z]{2})\s+(\d{5}(?:-\d{4})?)$", last)
            if m:
                props.setdefault("STATE", m.group(1).upper())
                props.setdefault("ZIP", m.group(2))

    return props


def load_sdk_config() -> dict[str, Any]:
    config_path = _config_path()
    if not config_path.exists():
        return {}
    try:
        data = json.loads(config_path.read_text(encoding="utf-8"))
    except Exception:
        return {}
    if not isinstance(data, dict):
        return {}
    return data


def save_sdk_config(data: dict[str, Any]) -> None:
    config_dir = _config_dir()
    config_path = _config_path()
    config_dir.mkdir(parents=True, exist_ok=True)
    tmp_path = config_path.with_suffix(".tmp")
    tmp_path.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8")
    tmp_path.replace(config_path)


def merge_sdk_config(**kwargs: Any) -> dict[str, Any]:
    data = load_sdk_config()
    for key, value in kwargs.items():
        if value is None:
            continue
        data[key] = value
    save_sdk_config(data)
    return data
