from __future__ import annotations

import argparse
import json
import shutil
from pathlib import Path

DEFAULT_TEMPLATE = "{root}/Clients/{client_code}/{fy}/{service}/"

def main():
    p = argparse.ArgumentParser()
    p.add_argument("--output", default="./agent_out", help="Output folder for generated agent package")
    p.add_argument("--branch-id", type=int, required=True)
    p.add_argument("--storage-root", required=True, help=r"Local storage root path (e.g. D:\AuditFirm\Tenant\Branch)")
    p.add_argument("--folder-template", default=DEFAULT_TEMPLATE)
    args = p.parse_args()

    out = Path(args.output).resolve()
    if out.exists():
        shutil.rmtree(out)
    out.mkdir(parents=True, exist_ok=True)

    cfg = {
        "branch_id": args.branch_id,
        "storage_root": args.storage_root,
        "folder_template": args.folder_template,
        "examples": [
            {"client_code": "C0001", "fy": "2025-26", "service": "GST"},
            {"client_code": "C0001", "fy": "2025-26", "service": "IT"},
        ],
    }

    (out / "branch_config.json").write_text(json.dumps(cfg, indent=2), encoding="utf-8")

    (out / "ensure_folders.py").write_text(
        '''
import json, os
from pathlib import Path

def render(tpl: str, root: str, client_code: str, fy: str, service: str) -> str:
    return tpl.replace("{root}", root).replace("{client_code}", client_code).replace("{fy}", fy).replace("{service}", service)

def ensure(path: str):
    Path(path).mkdir(parents=True, exist_ok=True)

def main():
    cfg = json.loads(Path("branch_config.json").read_text(encoding="utf-8"))
    root = cfg["storage_root"]
    tpl = cfg.get("folder_template", "{root}/Clients/{client_code}/{fy}/{service}/")

    for ex in cfg.get("examples", []):
        folder = render(tpl, root, ex["client_code"], ex["fy"], ex["service"])
        folder = folder.replace("/", os.sep)
        ensure(folder)
        print("Ensured:", folder)

if __name__ == "__main__":
    main()
'''.strip() + "\n",
        encoding="utf-8"
    )

    (out / "ensure_folders.bat").write_text(
        "@echo off\r\n"
        "python ensure_folders.py\r\n"
        "pause\r\n",
        encoding="utf-8"
    )

    print("Generated agent package at:", out)

if __name__ == "__main__":
    main()
