"""Config file handling for sdkspindle."""

import json
from pathlib import Path
from typing import Optional

CONFIG_NAME = ".sdkspindle.json"

DEFAULT_CONFIG = {
    "sdk_reference": "genai_sdk_reference.json",
    "include": ["**/*.kt", "**/*.java"],
    "exclude": ["**/test/**", "**/build/**", "**/generated/**"],
    "rules": {
        "OPTIONAL_NO_CALL": "error",
        "WRONG_TYPE": "error",
        "MISSING_ARGS": "error",
        "UNKNOWN_TYPE": "error",
        "MISSING_IMPORT": "error",
        "LISTOF_VARARGS": "warn",
        "STRING_ENUM": "warn"
    },
    "gemini_model": "gemini-3-flash-preview",
    "suppress_inline": True
}


def find_config() -> Optional[Path]:
    current = Path.cwd()
    while True:
        candidate = current / CONFIG_NAME
        if candidate.exists(): return candidate
        parent = current.parent
        if parent == current: break
        current = parent
    return None


def load_config() -> Optional[dict]:
    config_path = find_config()
    if not config_path: return None
    try:
        with open(config_path) as f:
            config = json.load(f)
        if "sdk_reference" in config:
            ref_path = Path(config["sdk_reference"])
            if not ref_path.is_absolute():
                config["sdk_reference"] = str(config_path.parent / ref_path)
        return config
    except (json.JSONDecodeError, OSError):
        return None


def generate_config(output_path=CONFIG_NAME):
    with open(output_path, "w") as f:
        json.dump(DEFAULT_CONFIG, f, indent=2)
        f.write("\n")
