from __future__ import annotations

import argparse
from pathlib import Path
import sys

import havelseiten as builder
import settings_config
import validate


ROOT_DIR = Path(__file__).resolve().parent.parent


def format_command() -> int:
    changed = settings_config.format_settings_file()
    settings_file = settings_config.active_settings_file()

    if not settings_file:
        print("Keine Einstellungsdatei gefunden.")
        return 1

    path = settings_file.relative_to(ROOT_DIR)

    if changed:
        print(f"formatiert: {path}")
    else:
        print(f"bereits formatiert: {path}")

    return 0


def validate_command() -> int:
    return validate.main()


def build_command() -> int:
    builder.build_site(format_settings=True)
    return 0


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        prog="havelseiten",
        description="Havelseiten formatieren, pruefen und bauen."
    )
    subparsers = parser.add_subparsers(dest="command", required=True)

    subparsers.add_parser(
        "format",
        help="havelseite/einstellungen.md formatieren"
    )
    subparsers.add_parser(
        "validate",
        help="Einstellungen und Markdown-Dateien pruefen"
    )
    subparsers.add_parser(
        "build",
        help="Website nach ausgabe/ bauen"
    )

    args = parser.parse_args(argv)

    if args.command == "format":
        return format_command()

    if args.command == "validate":
        return validate_command()

    if args.command == "build":
        return build_command()

    parser.print_help()
    return 1


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
