"""
Automation script for roadbook: {name} ({rb_id})
Generated by Roadbook CLI at {date_str}.

[AGENT INSTRUCTION - BEST PRACTICES]
1. Schema Sync [CRITICAL]: Modify the `TaskInput` and `TaskOutput` Pydantic models below to define your data contract. DO NOT manually edit `input_schema.json` or `output_schema.json` - they are generated automatically from these models.
2. Target URL: Target URLs are usually fixed for a specific task. Hardcode them in the script (e.g., `page.goto("https://...")`) instead of passing via `TaskInput` unless the script is explicitly designed for multiple domains.
3. State Passing: To pass variables between phase functions, use `rb.state` (a dictionary initialized in `run()`) or `rb.kv` (persistent KeyValue store).
4. Selectors: Prefer semantic locators (e.g., `page.get_by_role()`, `page.get_by_text()`) over brittle XPath/CSS.
5. Human Intervention: Use `rb.wait_for_human_action()` if the page requires login or has a CAPTCHA.
"""

from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field
from roadbook.sdk import RoadbookContext

# ==========================================
# 📋 I/O Contracts (Single Source of Truth)
# [AGENT INSTRUCTION] Update these models based on the user's requirements.
# ==========================================

class TaskInput(BaseModel):
    """Input parameters for the task"""
{input_model_fields}

class TaskOutput(BaseModel):
    """Extracted data structure"""
{output_model_fields}


# ==========================================
# ⚙️ Phase Functions
# ==========================================

{phase_functions}


# ==========================================
# 🚀 Main Execution
# ==========================================

def run():
{site_constraints_block}
    
    # Context manages everything automatically: ephemeral browsers, storage state saving/loading.
    with RoadbookContext(rb_id="{rb_id}", site_overrides=site_constraints) as rb:
        # Bind Pydantic models so the SDK can auto-generate JSON schemas and validate outputs
        rb.bind_schemas(input_model=TaskInput, output_model=TaskOutput)
        
        try:
            # 1. Parse and validate inputs
            raw_inputs = rb.get_inputs()
            inputs = TaskInput(**raw_inputs)
            
            # 2. State management for passing variables between phases
            rb.state = {}
            
            # 3. Execute phases sequentially
{phase_calls}
            
            rb.logger.info("🎉 All sheets completed successfully.")
            
        except Exception as e:
            rb.logger.error(f"❌ Task failed: {{str(e)}}")
            raise

if __name__ == "__main__":
    run()
