"""Generated file header formatting/parsing for Jaunt."""

from __future__ import annotations

import json
from typing import Literal

HEADER_MARKER = "# This file was generated by jaunt. DO NOT EDIT."


def format_header(
    *,
    tool_version: str,
    kind: Literal["build", "test"],
    source_module: str,
    module_digest: str,
    generation_fingerprint: str = "",
    module_context_digest: str = "",
    module_api_digest: str = "",
    spec_refs: list[str],
) -> str:
    digest = module_digest if module_digest.startswith("sha256:") else f"sha256:{module_digest}"
    spec_refs_json = json.dumps(spec_refs, ensure_ascii=True)
    lines = [
        HEADER_MARKER,
        f"# jaunt:tool_version={tool_version}",
        f"# jaunt:kind={kind}",
        f"# jaunt:source_module={source_module}",
        f"# jaunt:module_digest={digest}",
        f"# jaunt:spec_refs={spec_refs_json}",
    ]
    if module_context_digest:
        context_digest = (
            module_context_digest
            if module_context_digest.startswith("sha256:")
            else f"sha256:{module_context_digest}"
        )
        lines.insert(5, f"# jaunt:module_context_digest={context_digest}")
    if module_api_digest:
        api_digest = (
            module_api_digest
            if module_api_digest.startswith("sha256:")
            else f"sha256:{module_api_digest}"
        )
        lines.insert(5, f"# jaunt:module_api_digest={api_digest}")
    if generation_fingerprint:
        fingerprint = (
            generation_fingerprint
            if generation_fingerprint.startswith("sha256:")
            else f"sha256:{generation_fingerprint}"
        )
        lines.insert(5, f"# jaunt:generation_fingerprint={fingerprint}")
    return "\n".join(lines) + "\n"


def parse_header(source: str) -> dict[str, str] | None:
    """Parse the Jaunt header from the start of a file.

    Returns None if the file does not begin with the Jaunt header marker.
    """

    lines = source.splitlines()
    if not lines:
        return None
    if lines[0] != HEADER_MARKER:
        return None

    out: dict[str, str] = {}
    for line in lines[1:]:
        if not line.startswith("# jaunt:"):
            break
        rest = line[len("# jaunt:") :]
        if "=" not in rest:
            continue
        key, value = rest.split("=", 1)
        out[key.strip()] = value.strip()
    return out


def extract_module_digest(source: str) -> str | None:
    parsed = parse_header(source)
    if parsed is None:
        return None
    return parsed.get("module_digest")


def extract_generation_fingerprint(source: str) -> str | None:
    parsed = parse_header(source)
    if parsed is None:
        return None
    return parsed.get("generation_fingerprint")


def extract_module_context_digest(source: str) -> str | None:
    parsed = parse_header(source)
    if parsed is None:
        return None
    return parsed.get("module_context_digest")


def extract_module_api_digest(source: str) -> str | None:
    parsed = parse_header(source)
    if parsed is None:
        return None
    return parsed.get("module_api_digest")
