#!/usr/bin/env python3
"""Create a new phase's explicit settings before validating or pouring its plan."""
from __future__ import annotations

import argparse
import json
import sys

import repo_config
from sprint_index_common import DEFAULT_TEMPLATES, phase_config_path, validate_phase_config


def main(argv: list[str]) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    create = commands.add_parser("init", help="write new phase settings; never overwrite an existing phase")
    create.add_argument("--phase", required=True)
    create.add_argument("--lead", required=True, help="the appointed lead for this phase")
    args = parser.parse_args(argv)
    repo = repo_config.repo_root()
    path = phase_config_path(repo, args.phase)
    if path.exists():
        raise RuntimeError(f"{path} already exists; edit the tracked phase settings explicitly")
    config = repo_config.load(repo)
    data = {
        "plan": f"{config['plans_dir']}/phase-{args.phase}.jsonl",
        "root": f"{config['bead_prefix']}-phase-{args.phase}",
        "integration_branch": config["integration_branch_pattern"].format(phase=args.phase),
        "lead": args.lead,
        "templates": dict(DEFAULT_TEMPLATES),
    }
    validate_phase_config(repo, args.phase, data)
    scalars = "".join(f"{key} = {json.dumps(value, ensure_ascii=False)}\n"
                      for key, value in data.items() if key != "templates")
    templates = "".join(f"{key} = {json.dumps(value)}\n" for key, value in data["templates"].items())
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("x", encoding="utf-8") as stream:
        stream.write(scalars + "\n[templates]\n" + templates)
    print(path.relative_to(repo))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main(sys.argv[1:]))
    except (repo_config.ConfigError, RuntimeError, OSError, ValueError, KeyError) as exc:
        print(f"phase-config: {exc}", file=sys.stderr)
        raise SystemExit(2)
