#!/usr/bin/env python3
"""Auto-increment version and update changelog on deploy."""

import os
import sys
import json
from datetime import datetime
from pathlib import Path

BASE = Path(__file__).resolve().parent.parent
VERSION_FILE = BASE / "version.txt"
CHANGELOG_FILE = BASE / "CHANGELOG.md"


def read_version() -> tuple:
    try:
        parts = VERSION_FILE.read_text().strip().split(".")
        return tuple(int(p) for p in parts[:3])
    except (FileNotFoundError, ValueError):
        return (0, 0, 1)


def write_version(major: int, minor: int, patch: int):
    VERSION_FILE.write_text(f"{major}.{minor}.{patch}\n")


def bump_version(bump_type: str = "patch") -> str:
    major, minor, patch = read_version()
    if bump_type == "major":
        major += 1; minor = 0; patch = 0
    elif bump_type == "minor":
        minor += 1; patch = 0
    else:
        patch += 1
    write_version(major, minor, patch)
    return f"{major}.{minor}.{patch}"


def add_changelog_entry(version: str, features: list = None, fixes: list = None):
    date = datetime.now().strftime("%d.%m.%Y")
    lines = [f"\n## {version} ({date})"]
    if features:
        lines.append("### Новые функции\n" + "\n".join(f"- {f}" for f in features))
    if fixes:
        lines.append("### Исправления и улучшения\n" + "\n".join(f"- {f}" for f in fixes))
    entry = "\n".join(lines) + "\n"
    changelog = CHANGELOG_FILE.read_text(encoding="utf-8") if CHANGELOG_FILE.exists() else "# Changelog — AegisOne Service Portal\n"
    # Insert after the title line
    if changelog.startswith("# Changelog"):
        header_end = changelog.find("\n", changelog.find("\n", 2) + 1)
        if header_end == -1:
            changelog += entry
        else:
            changelog = changelog[:header_end] + entry + changelog[header_end:]
    else:
        changelog = f"# Changelog — AegisOne Service Portal\n{entry}\n" + changelog
    CHANGELOG_FILE.write_text(changelog, encoding="utf-8")


if __name__ == "__main__":
    bump = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] in ("major", "minor", "patch") else "patch"
    features = []
    fixes = []
    if len(sys.argv) > 2:
        try:
            parsed = json.loads(sys.argv[2])
            features = parsed.get("features", [])
            fixes = parsed.get("fixes", [])
        except (json.JSONDecodeError, TypeError):
            pass
    version = bump_version(bump)
    add_changelog_entry(version, features, fixes)
    print(f"Version bumped to {version}")
