"""Per-project config stored in .venvy/config.json"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Optional

VENVY_DIR = ".venvy"
CONFIG_FILE = "config.json"
DEFAULT_VENV = ".venv"
DEFAULT_REQ = "requirements.txt"


class Config:
    def __init__(self, venv_name: str = DEFAULT_VENV, req_file: str = DEFAULT_REQ, ipykernel: bool = False):
        self.venv_name = venv_name
        self.req_file = req_file
        self.ipykernel = ipykernel

    def to_dict(self) -> dict:
        return {"venv_name": self.venv_name, "req_file": self.req_file, "ipykernel": self.ipykernel}

    @classmethod
    def from_dict(cls, d: dict) -> "Config":
        return cls(d.get("venv_name", DEFAULT_VENV), d.get("req_file", DEFAULT_REQ), d.get("ipykernel", False))


def find_root(start: Optional[Path] = None) -> Optional[Path]:
    """Walk up to find project root containing .venvy/config.json"""
    cur = (start or Path.cwd()).resolve()
    for d in [cur, *cur.parents]:
        if (d / VENVY_DIR / CONFIG_FILE).exists():
            return d
    return None


def load(cwd: Optional[Path] = None) -> Optional[Config]:
    path = (cwd or Path.cwd()) / VENVY_DIR / CONFIG_FILE
    if not path.exists():
        return None
    try:
        return Config.from_dict(json.loads(path.read_text("utf-8")))
    except Exception:
        return None


def save(cfg: Config, cwd: Optional[Path] = None) -> None:
    path = (cwd or Path.cwd()) / VENVY_DIR / CONFIG_FILE
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(cfg.to_dict(), indent=2), "utf-8")
