from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path
from typing import Any


PACK_APPS_PATH = Path("runtime/prodsol_flow_005_versioned_apps.json")


def record_versioned_app_for_product_pack(
    *,
    app_code: str,
    version_name: str,
    resource_name: str,
) -> None:
    PACK_APPS_PATH.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "apps": [
            {
                "app_code": app_code,
                "version_name": version_name,
                "resource_name": resource_name,
                "created_at": datetime.now().isoformat(timespec="seconds"),
            }
        ]
    }
    PACK_APPS_PATH.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")


def load_versioned_app_codes_for_product_pack() -> list[str]:
    payload = _read_payload()
    codes: list[str] = []
    for record in payload.get("apps", []):
        app_code = str(record.get("app_code") or "").strip()
        if app_code and app_code not in codes:
            codes.append(app_code)
    return codes


def load_versioned_app_records_for_product_pack() -> list[dict[str, str]]:
    payload = _read_payload()
    records: list[dict[str, str]] = []
    for record in payload.get("apps", []):
        if not isinstance(record, dict):
            continue
        app_code = str(record.get("app_code") or "").strip()
        version_name = str(record.get("version_name") or "").strip()
        resource_name = str(record.get("resource_name") or "").strip()
        if not app_code or not version_name or not resource_name:
            continue
        records.append(
            {
                "app_code": app_code,
                "version_name": version_name,
                "resource_name": resource_name,
            }
        )
    return records


def _read_payload() -> dict[str, Any]:
    if not PACK_APPS_PATH.exists():
        return {"apps": []}
    try:
        payload = json.loads(PACK_APPS_PATH.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return {"apps": []}
    if not isinstance(payload, dict):
        return {"apps": []}
    if not isinstance(payload.get("apps"), list):
        payload["apps"] = []
    return payload
