from __future__ import annotations

import argparse
import sys
from pathlib import Path


def set_ini_value(lines: list[str], key: str, value: str) -> list[str]:
    prefix = f"{key}="
    output: list[str] = []
    found = False
    for line in lines:
        if line.lstrip().startswith(prefix):
            if not found:
                output.append(f"{key}={value}")
                found = True
            continue
        output.append(line)
    if not found:
        output.append(f"{key}={value}")
    return output


def main() -> int:
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        sys.stderr.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass

    parser = argparse.ArgumentParser(description="Save WeChat chat-log settings.")
    parser.add_argument("--config", required=True)
    parser.add_argument("--chat-log", required=True)
    parser.add_argument("--self-name", default="")
    parser.add_argument("--partner-name", default="")
    args = parser.parse_args()

    chat_log = Path(args.chat_log).expanduser()
    if not chat_log.exists():
        raise SystemExit(f"Chat log path not found: {chat_log}")

    config_path = Path(args.config).expanduser()
    if config_path.exists():
        text = config_path.read_text(encoding="utf-8-sig")
        lines = text.splitlines()
    else:
        lines = ["[DEFAULT]"]

    if not any(line.strip().lower() == "[default]" for line in lines):
        lines.insert(0, "[DEFAULT]")

    lines = set_ini_value(lines, "PREFERRED_RENDERER", "bibi")
    lines = set_ini_value(lines, "PET_SIZE", "160")
    lines = set_ini_value(lines, "CHAT_LOG_PATH", str(chat_log.resolve()))
    lines = set_ini_value(lines, "CHAT_SELF_NAME", args.self_name)
    lines = set_ini_value(lines, "CHAT_PARTNER_NAME", args.partner_name)

    config_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print("[OK] WeChat chat log imported:")
    print(f"     {chat_log.resolve()}")
    if args.self_name:
        print(f"[OK] Self name: {args.self_name}")
    if args.partner_name:
        print(f"[OK] Partner name: {args.partner_name}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
