"""Write generated agent/run.py script and .gitignore."""

from pathlib import Path


def write_generated_run(output_dir: Path) -> Path:
    """Write agent/run.py: thin script that runs the agent (for python agent/run.py)."""
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    content = '''# Generated by foremet - do not edit by hand.
"""Run the agent once. Usage: python run.py "your message" or foremet run for interactive chat."""
import sys
from pathlib import Path

# Repo root = parent of agent/ (where adk.config.json lives)
_AGENT_DIR = Path(__file__).resolve().parent
_CWD = _AGENT_DIR.parent if (_AGENT_DIR.parent / "adk.config.json").exists() else Path.cwd()

def main():
    from foremet.agent.runner import run_invoke
    msg = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else input("You: ").strip()
    if not msg:
        return
    result = run_invoke(cwd=_CWD, message=msg)
    for m in reversed(result.get("messages", [])):
        if m.__class__.__name__ == "AIMessage":
            print(m.content)
            break

if __name__ == "__main__":
    main()
'''
    path = output_dir / "run.py"
    path.write_text(content)
    # .gitignore so generated agent dir doesn't commit .env or cache
    (output_dir / ".gitignore").write_text(".env\n__pycache__/\n*.pyc\n")
    return path
