import os
import json
from pathlib import Path

CONFIG_DIR = Path.home() / ".cortif"
CONFIG_FILE = CONFIG_DIR / "config.json"
PROJECT_CONFIG_FILE = Path.cwd() / "cortif.json"

def save_api_key(api_key: str, host: str):
    CONFIG_DIR.mkdir(exist_ok=True)
    config = {"api_key": api_key, "host": host}
    with open(CONFIG_FILE, "w") as f:
        json.dump(config, f)
    os.chmod(CONFIG_FILE, 0o600)

def get_api_key_and_host():
    if not CONFIG_FILE.exists():
        return None, None
    with open(CONFIG_FILE, "r") as f:
        config = json.load(f)
        return config.get("api_key"), config.get("host")

def save_project_config(project_id: str, organization_id: str, run_id_template: str):
    config = {
        "project_id": project_id,
        "organization_id": organization_id,
        "run_id_template": run_id_template
    }
    with open(PROJECT_CONFIG_FILE, "w") as f:
        json.dump(config, f, indent=2)

def get_project_config():
    if not PROJECT_CONFIG_FILE.exists():
        return None
    with open(PROJECT_CONFIG_FILE, "r") as f:
        config = json.load(f)
        return config
