"""Hardhat compile & test runner for FHE contracts."""

import subprocess
import os
import re

HARDHAT_DIR = os.environ.get(
    'SOLAGENT_HARDHAT_DIR',
    '/root/projects/hackathon-fhenix/cofhe-hardhat-starter'
)


def run_compile(contract_path: str = None) -> dict:
    """Run hardhat compile. Returns {success, output, errors}."""
    cmd = ['npx', 'hardhat', 'compile']
    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        cwd=HARDHAT_DIR,
        timeout=120
    )

    output = result.stdout + result.stderr
    success = result.returncode == 0

    errors = []
    if not success:
        lines = output.split('\n')
        i = 0
        while i < len(lines):
            line = lines[i]
            if any(tag in line for tag in ['TypeError:', 'ParserError:', 'DeclarationError:', 'SyntaxError:']):
                block = [line.strip()]
                for j in range(1, 6):
                    if i + j < len(lines):
                        next_line = lines[i + j].strip()
                        if next_line.startswith('Error HH') or next_line.startswith('HardhatError'):
                            break
                        block.append(next_line)
                errors.append('\n'.join(block))
                i += len(block)
                continue
            i += 1

    clean_output = '\n\n'.join(errors) if errors else output

    return {
        'success': success,
        'output': clean_output,
        'errors': errors
    }


def run_test(test_file: str = None) -> dict:
    """Run hardhat test. Returns {success, output, passed, failed}."""
    cmd = ['npx', 'hardhat', 'test']
    if test_file:
        cmd.append(test_file)

    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        cwd=HARDHAT_DIR,
        timeout=180
    )

    output = result.stdout + result.stderr
    success = result.returncode == 0

    passing = 0
    failing = 0
    match_pass = re.search(r'(\d+) passing', output)
    match_fail = re.search(r'(\d+) failing', output)
    if match_pass:
        passing = int(match_pass.group(1))
    if match_fail:
        failing = int(match_fail.group(1))

    return {
        'success': success,
        'output': output,
        'passed': passing,
        'failed': failing
    }


def write_contract(name: str, code: str) -> str:
    """Write contract to cofhe-hardhat-starter/contracts/. Returns path."""
    if not name.endswith('.sol'):
        name += '.sol'
    path = os.path.join(HARDHAT_DIR, 'contracts', name)
    with open(path, 'w') as f:
        f.write(code)
    return path


def read_contract(name: str) -> str:
    """Read contract source."""
    if not name.endswith('.sol'):
        name += '.sol'
    path = os.path.join(HARDHAT_DIR, 'contracts', name)
    with open(path) as f:
        return f.read()
