"""Agent for the vaultgen project."""

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

from pydantic_ai import Agent

from .instructions import get_instructions
from .schema import load_schema

MODEL = "google-gla:gemini-3-flash-preview"


def initialize_agent(vault: Path) -> Agent[None, Any]:
    """Initialize the agent for the vaultgen project."""
    schema = load_schema(vault)

    agent = Agent(
        model=MODEL,
        instructions=get_instructions(vault),
        output_type=list[schema] | schema | str,
        output_retries=3,
    )

    @agent.system_prompt
    def _vault_status() -> str:
        parts = []
        if not vault.is_dir():
            return "(There are no notes yet.)"

        for md_path in sorted(vault.rglob("*.md")):
            if md_path.name.lower() == "config.md":
                continue
            try:
                text = md_path.read_text(encoding="utf-8", errors="replace")
                rel = md_path.relative_to(vault)
                parts.append(f"== {rel} ==\n{text}\n")
            except OSError:
                continue

        if len(parts) == 0:
            return "(There are no notes yet.)"

        return "**Current state of the vault:**\n\n" + "\n".join(parts)

    @agent.system_prompt
    def _timestamp() -> str:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        return f"The current date and time is {now}."

    return agent
