"""Auto-learned skill generated by GPIA."""

from typing import Any, Dict

from skills.base import Skill, SkillCategory, SkillContext, SkillLevel, SkillMetadata, SkillResult

def solve(task: str, context: dict) -> object:
    import math
    import re
    task_text = task or "Calculate the square root of 123456789, multiply it by pi, and write the result to a file named 'bench_test_bbeda5ee.txt'."
    lower = task_text.lower()
    numbers = re.findall(r"\d+", task_text)
    value = float(numbers[0]) if numbers else None
    if value is not None and "square root" in lower:
        value = math.sqrt(value)
    if value is not None and "pi" in lower:
        value = value * math.pi
    match = re.search(r"file (?:named|called) ['\"]([^'\"]+)['\"]", task_text, re.IGNORECASE)
    target = match.group(1) if match else None
    if target and value is not None:
        with open(target, "w", encoding="utf-8") as handle:
            handle.write(str(value))
    return {"result": value, "file": target}


class AutoLearnedSkill(Skill):
    _cached_metadata: SkillMetadata = None

    def metadata(self) -> SkillMetadata:
        if AutoLearnedSkill._cached_metadata is None:
            AutoLearnedSkill._cached_metadata = SkillMetadata(
                id="auto_learned/calculate_the_square_root_of_123456789_m_aaf048df",
                name="Auto Learned calculate_the_square_root_of_123456789_m",
                description="Auto-learned skill for: Calculate the square root of 123456789, multiply it by pi, and write the result to a file named 'bench_test_bbeda5ee.txt'.",
                category=SkillCategory.AUTOMATION,
                level=SkillLevel.INTERMEDIATE,
                tags=["auto-learned", "drafted"],
            )
        return AutoLearnedSkill._cached_metadata

    def execute(self, input_data: Dict[str, Any], context: SkillContext) -> SkillResult:
        task = input_data.get("task", "")
        payload = input_data.get("context", input_data)
        try:
            result = solve(task, payload)
        except Exception as exc:
            return SkillResult(
                success=False,
                output=None,
                error=str(exc),
                error_code="AUTO_LEARNED_ERROR",
                skill_id=self.metadata().id,
            )
        output = result if isinstance(result, dict) else {"result": result}
        return SkillResult(
            success=True,
            output=output,
            skill_id=self.metadata().id,
        )
