from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))
for dep_dir in [SCRIPT_DIR / ".pydeps", SCRIPT_DIR.parent / ".pydeps", Path.cwd() / ".pydeps"]:
    if dep_dir.exists() and str(dep_dir) not in sys.path:
        sys.path.insert(0, str(dep_dir))

from PIL import Image, ImageDraw, ImageFont
import yaml

from runtime_config import add_config_source_args, load_runtime_config


def load_font(size: int, *, bold: bool = False) -> ImageFont.ImageFont:
    candidates: list[str] = []
    if bold:
        candidates.extend([r"C:\Windows\Fonts\msyhbd.ttc", r"C:\Windows\Fonts\simhei.ttf", r"C:\Windows\Fonts\arialbd.ttf"])
    candidates.extend([r"C:\Windows\Fonts\msyh.ttc", r"C:\Windows\Fonts\simsun.ttc", r"C:\Windows\Fonts\arial.ttf"])
    for p in candidates:
        try:
            return ImageFont.truetype(p, size=size)
        except OSError:
            continue
    return ImageFont.load_default()


def resize_to_width(img: Image.Image, width: int) -> Image.Image:
    if img.width == width:
        return img
    h = max(1, int(img.height * width / img.width))
    return img.resize((width, h), Image.Resampling.LANCZOS)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Compose goods-effect flow images into one report.")
    add_config_source_args(parser, default_config=Path(r"D:\projects\skills\vip-report\config.yaml"))
    parser.add_argument("--summary-image", default="")
    parser.add_argument("--top5-image", default="")
    parser.add_argument("--output", default="")
    parser.add_argument("--content-width", type=int, default=0, help="0 = auto use max source width")
    return parser.parse_args()


def defaults_from_config(cfg: dict[str, Any]) -> dict[str, Path]:
    workdir = Path(cfg["paths"]["workdir"]).resolve()
    base = workdir / "assets" / "cep-live-goods-effect"
    return {
        "summary": base / "cep-live-goods-effect-summary.png",
        "top5": base / "cep-live-goods-effect-top5.png",
        "output": base / "cep-live-goods-effect-combined.png",
    }


def resolve(p: str, default: Path) -> Path:
    return Path(p).resolve() if p else default


def main() -> None:
    args = parse_args()
    config_path = Path(args.config or r"D:\projects\skills\vip-report\config.yaml").resolve()
    cfg = load_runtime_config(args, default_config=config_path)
    defaults = defaults_from_config(cfg)
    summary_path = resolve(args.summary_image, defaults["summary"])
    top5_path = resolve(args.top5_image, defaults["top5"])
    output_path = resolve(args.output, defaults["output"])

    if not summary_path.exists():
        raise FileNotFoundError(f"summary image not found: {summary_path}")
    if not top5_path.exists():
        raise FileNotFoundError(f"top5 image not found: {top5_path}")

    summary_img = Image.open(summary_path).convert("RGB")
    top5_img = Image.open(top5_path).convert("RGB")

    content_w = args.content_width if args.content_width > 0 else max(summary_img.width, top5_img.width)
    summary_img = resize_to_width(summary_img, content_w)
    top5_img = resize_to_width(top5_img, content_w)

    pad_x = 24
    top_h = 56
    gap = 10
    bottom_pad = 16
    canvas_w = content_w + pad_x * 2
    canvas_h = top_h + summary_img.height + gap + top5_img.height + bottom_pad

    canvas = Image.new("RGB", (canvas_w, canvas_h), "#e7e7e7")
    draw = ImageDraw.Draw(canvas)
    draw.text((pad_x, 12), "LIVE GOODS EFFECT", fill="#111111", font=load_font(34, bold=True))
    draw.text((canvas_w - 200, 16), "CHARLES & KEITH", fill="#c9c9c9", font=load_font(24, bold=True))

    y = top_h
    canvas.paste(summary_img, (pad_x + (content_w - summary_img.width) // 2, y))
    y += summary_img.height + gap
    canvas.paste(top5_img, (pad_x + (content_w - top5_img.width) // 2, y))

    output_path.parent.mkdir(parents=True, exist_ok=True)
    canvas.save(output_path)
    print(json.dumps({"ok": True, "image_path": str(output_path)}, ensure_ascii=False))


if __name__ == "__main__":
    main()
